javascript / expert
Snippet
Manual Component Instantiation with ViewContainerRef
Using ViewContainerRef.createComponent allows for the imperative instantiation of components at runtime. This bypasses static template definitions, enabling complex scenarios like dynamic dashboards, ad banners, or modular UI layouts where the component type is determined by data or configuration.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
@Directive({ selector: '[adHost]' })export class AdDirective { constructor(public vcr: ViewContainerRef) {} }@Component({ ... })export class AdBannerComponent {@ViewChild(AdDirective, { static: true }) adHost!: AdDirective;loadComponent(componentType: Type<any>) {this.adHost.vcr.clear();const ref = this.adHost.vcr.createComponent(componentType);ref.instance.data = { status: 'Dynamic Content' };}}
angular
Breakdown
1
this.adHost.vcr.clear();
Removes previously rendered dynamic content from the container.
2
this.adHost.vcr.createComponent(componentType)
Instantiates the component and attaches it to the DOM.
3
ref.instance.data = ...
Accesses the component instance to set inputs manually.