无法阅读 属性 'createComponent'?
Cannot read property 'createComponent'?
完整代码为:
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);
创建组件是,returns特定组件:
switch (this.type) {
case "profile":
return SaveProfileDialogComponent;
case "project":
return SaveProjectDialogComponent;
}
}
在聊天并查看您的整个代码后,由于 *ngFor 条件,您尝试访问的带有 child 的容器似乎尚未在屏幕上生成,请务必注意,您只能如果已经生成,则使用 @viewChild 访问 child。乐于助人!
完整代码为:
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);
创建组件是,returns特定组件:
switch (this.type) {
case "profile":
return SaveProfileDialogComponent;
case "project":
return SaveProjectDialogComponent;
}
}
在聊天并查看您的整个代码后,由于 *ngFor 条件,您尝试访问的带有 child 的容器似乎尚未在屏幕上生成,请务必注意,您只能如果已经生成,则使用 @viewChild 访问 child。乐于助人!