Reputation: 65
I'm trying to dynamically load components inside, unsubscribeDisclaimer
.
Below is my HTML
<ng-template #TooltipInfo>
<p #unsubscribeDisclaimer></p>
</ng-template>
In Component.ts
@ViewChild('unsubscribeDisclaimer', { read: ViewContainerRef, static: true }) unsubscribeDisclaimer: ViewContainerRef;
this.createComponent(unsubscribeDisclaimer, this.unsubscribeDisclaimer);
createComponent (content, view: ViewContainerRef) {
console.log(view);
const componentType = this.contentMappings[content.type];
if(view) {
this.componentFactory = this.componentFactoryResolver.resolveComponentFactory(componentType);
this.componentReference = view.createComponent(this.componentFactory);
this.componentReference.instance.contentOnCreate(content);
}
}
But for unknown reasons, view is undefined
What I'm doing wrong here ?
Upvotes: 1
Views: 1690
Reputation: 65
Changing the static
value to false
worked.
@ViewChild('unsubscribeDisclaimer', { read: ViewContainerRef, static: false }) unsubscribeDisclaimer: ViewContainerRef;
Upvotes: 0
Reputation: 2004
You can take this approach: don't create directive, instead give an Id to ng-template
<ng-template #dynamicComponent></ng-template>
use @ViewChild
decorator inside your component class
@ViewChild('dynamicComponent', { read: ViewContainerRef }) myRef
ngAfterViewInit() {
const factory = this.componentFactoryResolver.resolveComponentFactory(component);
const ref = this.myRef.createComponent(factory);
ref.changeDetectorRef.detectChanges();
}
Hope you can apply this in your approach.
Upvotes: 1