javascript / expert
Snippet
Programmatic Component Orchestration via ViewContainerRef
Dynamic component loading allows for highly flexible UIs where components are instantiated at runtime based on logic rather than templates. ViewContainerRef provides the API to clear containers and inject new components, while the setInput API (introduced in Angular 14) ensures signal-safe input binding.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
@Directive({ selector: '[adHost]' })export class AdDirective {constructor(public viewContainerRef: ViewContainerRef) {}loadDynamicComponent(componentType: Type<any>, data: any) {this.viewContainerRef.clear();const componentRef = this.viewContainerRef.createComponent(componentType);componentRef.setInput('data', data);componentRef.instance.outputEmitter.subscribe(event => handle(event));}}
angular
Breakdown
1
this.viewContainerRef.clear();
Removes any existing components or views from this container to prevent stacking.
2
this.viewContainerRef.createComponent(componentType);
Instantiates the specified component class and inserts its host view into this container.
3
componentRef.setInput('data', data);
Programmatically sets an @Input property on the dynamic component instance in a change-detection-friendly way.