I want to create components dynamically from an array. #cmp1, #cmp2, #cmp3 should be dynamic how can this be achieved
 <my-component #cmp1></my-component> 
 <my-component #cmp2></my-component> 
 <my-component #cmp3></my-component> 
 componentList: string[] = ['cmp1', 'cmp2', 'cmp3']
And I have to fetch one these components dynamically at runtime based on a string value
 let reqiuredComponent = 'cmp2'
 let captureComponent: MyComponent = @ViewChild(requiredComponent)
This can be achieved without assigning dynamic template reference [#cp1, #cp2 ...] also.
In your .html
<div #container>
 <ng-container #main></ng-container>
</div>
In your .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)); 
    }           
  }
Now to access your different component
console.log(this.container.nativeElement.childNodes[1]     //childNodes[0|1|2]
Like this you can assess all the functionality of ElementRef like ...childNodes[0].innerHTML
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With