我正在尝试显示一个类似于(不完全) Angular 文档中示例的动态组件。
我有一个带有 viewContainerRef 的动态指令
@Directive({
selector: '[dynamicComponent]'
})
export class DynamicComponentDirective {
constructor(public viewContainerRef: ViewContainerRef) { }
}
组件代码摘录
@ViewChild(DynamicComponentDirective) adHost: DynamicComponentDirective;
..
ngAfterViewInit() {
let componentFactory = null;
console.log(component);
componentFactory = this.componentFactoryResolver.resolveComponentFactory(component);
// this.adHost.viewContainerRef.clear();
const viewContainerRef = this.adHost.viewContainerRef;
viewContainerRef.createComponent(componentFactory);
}
最后添加<ng-template dynamicComponent></ng-template>
在模板中
最佳答案
我遇到了同样的问题。您必须将指令添加到 AppModule 中:
@NgModule({
declarations: [
AppComponent,
...,
YourDirective,
],
imports: [
...
],
providers: [...],
bootstrap: [AppComponent],
entryComponents: [components to inject if required]
})
关于angular - 无法读取未定义的属性 'viewContainerRef',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48330760/