【问题标题】:Angular 8 adding component dynamically "viewContainerRef of undefined" errorAngular 8动态添加组件“未定义的viewContainerRef”错误
【发布时间】: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


    【解决方案1】:

    我知道这是一个老问题,但几天前我遇到了同样的问题: 从 ngOnInit() 调用使用 alertHost 的方法。

    为确保@ViewChild 注入的引用存在,总是使用 ngAfterViewInit() 编写初始化代码。

    除了从 ngAfterViewIinit 调用 showMyComp 之外,我还必须将 @ViewChild 更新为以下内容:

    @ViewChild(PlaceholderDirective, {static: false}) alertHost: PlaceholderDirective;

    (这部分可能是由于不同的角度版本造成的)

    【讨论】:

      猜你喜欢
      • 2020-10-10
      • 2018-09-21
      • 1970-01-01
      • 2019-12-19
      • 2018-12-01
      • 1970-01-01
      • 2019-06-03
      • 2020-10-03
      • 2017-10-27
      相关资源
      最近更新 更多