javascript / expert
Snippet
Manuelle Komponenten-Instanziierung mit ViewContainerRef
Die Verwendung von ViewContainerRef.createComponent ermöglicht die imperative Instanziierung von Komponenten zur Laufzeit. Dies umgeht statische Template-Definitionen und ermöglicht komplexe Szenarien wie dynamische Dashboards, Werbebanner oder modulare UI-Layouts, bei denen der Komponententyp durch Daten oder Konfiguration bestimmt wird.
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
Erklärung
1
this.adHost.vcr.clear();
Entfernt zuvor gerenderten dynamischen Inhalt aus dem Container.
2
this.adHost.vcr.createComponent(componentType)
Instanziiert die Komponente und hängt sie an den DOM an.
3
ref.instance.data = ...
Greift auf die Komponenteninstanz zu, um Inputs manuell zu setzen.