3

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?

roadkiII
  • 161
  • 2
  • 5

2 Answers2

1

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;
    });
}
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
1
then(cmpRef:ComponentRef => {
  cmpRef.instance.myProp = someValue;
  cmpRef.instance.someOutput.subscribe(val => this.someOtherOutput.next(val));
});

See also Angular 2 dynamic tabs with user-click chosen components for the new way ViewContainerRef.createComponent().

DynamicComponentLoader is deprecated.

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567