I can create a component dynamically and project some template inside it just fine with the following code -
@Component({
selector: 'dynamic',
template: `
<p>Dynamic Component</p>
<ng-content></ng-content>
`
})
export class DynamicComponent { }
@Component({
selector: 'tester',
template: `
<p>Tester Component</p>
<ng-container #cnt></ng-container>
<ng-template #tpl>
<p>[Projected Content]</p>
</ng-template>
`
})
export class TesterComponent implements AfterViewInit {
@ViewChild('cnt', { read: ViewContainerRef }) cnt: ViewContainerRef
@ViewChild('tpl') tpl: TemplateRef<any>
ngAfterViewInit(): void {
let content = [this.tpl.createEmbeddedView(null).rootNodes];
this.cnt.createComponent(DynamicComponent, { projectableNodes: content });
}
}
But I want to project another component (e.g. the following one) inside the dynamic component -
@Component({
selector: 'content',
template: `<p>Content Component</p>`
})
export class ContentComponent { }
so that the resulting output becomes the equivalent of -
<p>Tester Component</p>
<dynamic>
<content></content>
</dynamic>
Cannot figure out how to achieve that. Any help/suggestion would be appreciated. Thanks.
UPDATE
We can use the
createComponentAPI to dynamically create the component and then usingcontentRef.location.nativeElementproject the content onto the dynamic created component, note the double array syntax, that got this working!test.ts
Stackblitz Demo
We can just access the content using
ContentChildand then using a or condition, we can either use the content child, or use the view child, whichever is present in the defined order!ts
main.ts
Stackblitz Demo