I'm trying to inject a component on a container dinamically
Component:
@Component({...})
export class InvestmentProcess{
@ViewChild('container') container;
constructor(public dcl: DynamicComponentLoader) {}
loadComponent(fooComponent: Type){
this.dcl.loadNextToLocation(fooComponent, container);
}
}
Template:
<div #container> </div>
When I run the function loadComponent the following error is thrown:
TypeError: location.createComponent is not a function
That's becouse container is an ElementRef typed variable, and loadNextToLocation expects a ViewContainerRef as the second parameter. As official docs said, the ViewContainerRef can be extracted from an element via @ViewChild, but I haven't find any example to do it properly.
Working with Angular2.0.0rc1
DynamicComponentLoader is going to be deprecated. Use ViewContainerRef.createComponent()
@Component({...})
export class InvestmentProcess{
@ViewChild('container', {read: ViewContainerRef}) container:ViewContainerRef;
constructor(private resolver: ComponentResolver) {}
loadComponent(fooComponent: Type){
this.resolver.resolveComponent(fooComponent).then((factory:ComponentFactory<any>) => {
this.cmpRef = this.target.createComponent(factory)
});
}
}
See also Angular 2 dynamic tabs with user-click chosen components
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