Как динамически назвать элемент в угловых - PullRequest
1 голос
/ 04 мая 2019

Я хочу создавать компоненты динамически из массива.# cmp1, # cmp2, ​​# cmp3 должны быть динамическими, как этого можно достичь

 <my-component #cmp1></my-component> 
 <my-component #cmp2></my-component> 
 <my-component #cmp3></my-component> 

 componentList: string[] = ['cmp1', 'cmp2', 'cmp3']

И мне нужно динамически выбирать один из этих компонентов во время выполнения на основе строкового значения

 let reqiuredComponent = 'cmp2'
 let captureComponent: MyComponent = @ViewChild(requiredComponent)

1 Ответ

1 голос
/ 05 мая 2019

Этого можно достичь, не назначая динамическую ссылку на шаблон [#cp1, #cp2 ...] также.

В вашем .html

<div #container>
 <ng-container #main></ng-container>
</div>

В вашем .ts

  @ViewChild('main', {read: ViewContainerRef}) vcr: ViewContainerRef;
  @ViewChild('container') container: ElementRef;

  constructor(private cfr: ComponentFactoryResolver,
              private el: ElementRef) {}

  ngAfterViewInit() { 
    for(let i=0; i<3; i++) {
      this.vcr.createComponent(this.cfr.resolveComponentFactory(MyComponent)); 
    }           
  }

Теперь доступ ваш другой компонент

console.log(this.container.nativeElement.childNodes[1]     //childNodes[0|1|2]

Таким образом, вы можете оценить все функциональные возможности ElementRef, как ...childNodes[0].innerHTML

...