ViewContainerRef в Angular позволяет динамически создавать компоненты и внедрять в них зависимости. Сначала нужно получить доступ к ViewContainerRef через @ViewChild, затем использовать метод createComponent для создания экземпляра компонента. После создания можно передать данные через инстанс компонента.Пример:
@Component({
selector: 'app-dynamic-host',
template: `<ng-container #container></ng-container>`,
})
export class DynamicHostComponent {
@ViewChild('container', { read: ViewContainerRef, static: true })
container!: ViewContainerRef;
loadComponent() {
const componentRef = this.container.createComponent(DynamicComponent);
componentRef.instance.data = 'Переданные данные';
}
}
@Component({
selector: 'app-dynamic-component',
template: `<p>{{ data }}</p>`,
})
export class DynamicComponent {
data!: string;
}
👉 @sWebDev
