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?
2 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;
});
}
Comments
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.