完整代码为:
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;
}
}
聊天并看到完整的代码后,由于* ngFor条件,似乎尚未在屏幕上生成您尝试访问的子容器,请注意,只有在以下情况下,您才可以使用@viewChild访问子容器:它已经生成。乐于帮助!