【发布时间】:2020-06-06 14:59:15
【问题描述】:
我正在学习 Angular 并尝试以编程方式将组件添加到我的 HTML 中。但是,我收到以下错误:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'viewContainerRef' of undefined
以下是代码的关键部分。
我的占位符指令:
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appPlaceholder]'
})
export class PlaceholderDirective {
constructor(public viewContainerRef: ViewContainerRef) {}
}
Main.component.ts:
export class MainComponent implements OnInit {
@ViewChild(PlaceholderDirective, {static: false, read: ViewContainerRef}) alertHost: PlaceholderDirective;
constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
ngOnInit(): void {
this.showMyComp();
}
private showMyComp() {
const testCmpFactory = this.componentFactoryResolver.resolveComponentFactory(TestComponent);
const hostViewContainerRef = this.alertHost.viewContainerRef;
hostViewContainerRef.clear();
hostViewContainerRef.createComponent(testCmpFactory);
}
}
Main.component.html:
<ng-template appPlaceholder></ng-template>
我已将问题缩小到 MainComponent.ts 中的 const hostViewContainerRef = this.alertHost.viewContainerRef;。问题是 this.alertHost 为空,但我一直无法弄清楚原因。
【问题讨论】:
标签: components angular8 programmatically-created