Подтвердить что ты не робот

Angular 2 добавить динамику компонента в DOM или шаблон

Я планирую добавить динамический компонент в DOM, если вызывается show(). Я знаю, что есть решение с ngIf или [hidden], чтобы скрыть его и использовать в качестве директивы, но я не поклонник этого решения, потому что я не хочу объявлять его в своем HTML.

  import {Component} from 'angular2/core';
  import {InfoData} from '../../model/InfoData';

  @Component({
    selector: 'Info',
    templateUrl: './components/pipes&parts/info.html',
    styleUrls: ['./components/pipes&parts/info.css']
  })

  export class Info{
    infoData: InfoData;

    public show(infoData: InfoData) {
      this.infoData= infoData;
      document.body.appendChild(elemDiv); <----- Here?
    }
  }

а затем объявляю это как провайдера, поэтому я могу вызвать show().

  import {Component} from 'angular2/core';
  import {Info} from './components/pipes&parts/Info';

  @Component({
    selector: 'Admin',
    templateUrl: './Admin.html',
    styleUrls: ['./Admin.css'],
    directives: [Info],
    providers: [Info]
  })

  export class Admin {
    constructor(private info: Info) {
    info.show(); <---- append the Info Element to DOM
  }
4b9b3361

Ответ 1

Я не думаю, что вам нужно предоставить компонент Info в качестве поставщиков для другого компонента. Я не уверен, что он работает. Вы можете использовать Query и QueryView для сравнения компонентов, используемых в другом:

@Component({
  selector: 'Admin',
  templateUrl: './Admin.html',
  styleUrls: ['./Admin.css'],
  directives: [Info]
})
export class Admin{
  constructor(private @Query(Info) info: QueryList<Info>) {
    info.first().show(); <---- append the Info Element to DOM
  }
}

Вместо добавления элемента в компонент Info вы можете динамически добавлять этот компонент с помощью DynamicComponentLoader, как предложено Günter:

@Component({
  selector: 'Info',
  templateUrl: './components/pipes&parts/info.html',
  styleUrls: ['./components/pipes&parts/info.css']
})

export class Info{
      infoData: InfoData;

  public show(infoData: InfoData) {
    this.infoData= infoData;
    // No need to add the element dynamically
    // It now part of the component template
    // document.body.appendChild(elemDiv); <----- Here?
  }
}

@Component({
  selector: 'Admin',
  //templateUrl: './Admin.html',
  // To show where the info element will be added
  template: `
    <div #dynamicChild>
      <!-- Info component will be added here -->
    </div>
  `,
  styleUrls: ['./Admin.css'],
  directives: [Info]
})
export class Admin{
  constructor(private dcl: DynamicComponentLoader, private eltRef:ElementRef) {
    this._dcl.loadIntoLocation(Info, this._el, 'dynamicChild')
        .then(function(el) {
          // Instance of the newly added component
        });
  }
}

Надеюсь, это поможет вам, Thierry

Ответ 2

UPDATE

Используйте ViewContainerRef.createComponent()

Для полного примера см. Angular 2 динамических вкладки с выбранными вами компонентами, выбранными пользователем

ОРИГИНАЛ

DynamicComponentLoader был удален давно

Вы можете использовать DynamicComponentLoader для этой цели, но это немного громоздко и имеет некоторые проблемы, связанные с привязками.

См. также: