I'm building a small reference application to see how to dynamically inject components in one component to view the content on the page. I'm getting an error that points to the ViewContainerRef object.
This is the component that should display the injected component's content in the view, but it's throwing an error:
Here is the StatsComponent that is throwing the error:
export class StatsComponent implements AfterViewInit, OnDestroy {
@Input() dynComp: DynamicComponent;
@ViewChild(ComponentHostDirective) appComponentHost: ComponentHostDirective;
componentRef: ComponentRef<any>;
constructor(private componentFactoryResolver: ComponentFactoryResolver) { }
ngAfterViewInit() {
this.loadComponent();
}
ngOnDestroy() {
this.componentRef.destroy();
}
loadComponent() {
console.log('inside stats component: ', this.dynComp);
const comp = this.dynComp;
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(comp.component);
console.log('host: ', this.appComponentHost); // <-- this is undefined
const viewContainerRef = this.appComponentHost.viewContainerRef;
viewContainerRef.clear();
this.componentRef = viewContainerRef.createComponent(componentFactory);
(<DynamicComponent>this.componentRef.instance).data = comp.data;
}
}
I have a working demo here, and a github project.
Why is the container not being referenced?
[UPDATE]: this now works! Go to my demo and github project to see it in action.