Render dynamic components in Angular using ViewContainerRef:
A view container is a node in Angular's component tree that can contain content. Any component or directive can inject ViewContainerRef to get a reference to a view container corresponding to that component or directive's location in the DOM.
@Component({
selector: 'leaf-content',
template: `
This is the leaf content
`,
})
export class LeafContent {}
@Component({
selector: 'outer-container',
template: `
<p>This is the start of
the outer container</p>
<inner-item />
<p>This is the end of
the outer container</p>
`,
})
export class OuterContainer {}
@Component({
selector: 'inner-item',
template: `
<button
(click)="loadContent()">Load content</button>
`,
})
export class InnerItem {
constructor(private
viewContainer: ViewContainerRef) {}
loadContent() {
this.viewContainer.createComponent(LeafContent);
}
}
In the example above, clicking the
"Load Content" button results in the following DOM structure
<outer-container>
<p>This is the start of
the outer container</p>
<inner-item>
<button>Load
content</button>
</inner-item>
<leaf-content>This is the
leaf content</leaf-content>
<p>This is the end of the
outer container</p>
</outer-container>
This is the YouTube video link for
this: - https://youtu.be/8tRTmn-AWhE