angular - 无法读取未定义的属性 'viewContainerRef'

标签 angular angular-directive angular-components

我正在尝试显示一个类似于(不完全) 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/

相关文章:

Angular 4复选框更改值

angular - 在 MEAN 应用程序中使用 passport-facebook 进行 facebook 登录时出现 CORS 错误

javascript - 在模板中非法使用 ng-Transclude 指令

Angular 在使用指令时给出@angular/core 404 not found 错误

Angular默认子路由未加载父组件

javascript - Angular 2 和自定义下拉菜单

html - 如何在 Angular 2中使用ngFor循环遍历数组直到只有一些对象

angularjs - 如何在 angularjs 中上传 <img src> 中已有的图像

angular-cli - 角度 5 延迟加载与动态加载

javascript - 如何防止以 Angular2+ 的 react 形式重复调用 onChange 回调?