Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling methods in dynamically created component angular 2

Tags:

angular

I need to add components dynamically from triggered events, i´ve managed to get it working with loadasroot and loadnexttolocation, but the problem is that those only return a promise for the ComponentRef and i cant find a wat to access properties and calling methods in the added components. Ive read some threads about the loadintolocation but it seems that they removed that after releasing the candidate?

like image 372
roadkiII Avatar asked Mar 06 '26 11:03

roadkiII


1 Answers

Now you can use the ComponentResolver class this way. On the ComponentRef instance, you can access both properties and methods of the newly created component.

@ViewChild('target', {read: ViewContainerRef}) target;

constructor(private resolver: ComponentResolver) {}

createComponent() {
  this.resolver.resolveComponent(MyComp).then(
    (factory:ComponentFactory<any>) => {
      var cmpRef = this.target.createComponent(factory);
      var cmp = cmpRef.instance;
    });
}
like image 162
Thierry Templier Avatar answered Mar 09 '26 00:03

Thierry Templier