无法读取属性“ createComponent”?

时间:2019-11-20 17:53:22

标签: angular angular7 angular8

完整代码是:

export class FileSaveDialogComponent
  implements OnInit, AfterViewInit, OnDestroy {
   @ViewChild("target", { read: ViewContainerRef, static: true }) target;

    ngAfterViewInit() {
    console.log(this.target);
    const component = this.createComponent();
    const factory = this.resolver.resolveComponentFactory(component);
    this.componentRef = this.target.createComponent(factory);
  }

}

HTML是:

<div class="savefile-content" #target></div>

使用:

<vr-savefile-dialog
  (saveCallback)="saveCallback($event)"
  [title]="'Save profile'"
  [type]="'profile'"
></vr-savefile-dialog>

为什么我收到错误消息:

ERROR TypeError: Cannot read property 'createComponent' of undefined
    at FileSaveDialogComponent.ngAfterViewInit

并且未在行中定义:

console.log(this.target);

创建组件是,它返回特定的组件:

    switch (this.type) {
      case "profile":
        return SaveProfileDialogComponent;
      case "project":
        return SaveProjectDialogComponent;
    }
  }

1 个答案:

答案 0 :(得分:2)

聊天并查看完整的代码后,由于* ngFor条件,似乎尚未在屏幕上生成您尝试访问的子容器,请注意,您只能使用@viewChild访问子容器如果已经生成。乐意提供帮助!