Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically name element in angular

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)
like image 242
Jaya Venkat Avatar asked Oct 29 '25 07:10

Jaya Venkat


1 Answers

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

like image 118
Prashant Avatar answered Oct 31 '25 01:10

Prashant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!