Full code is:
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 is:
<div class="savefile-content" #target></div>
Using:
<vr-savefile-dialog
(saveCallback)="saveCallback($event)"
[title]="'Save profile'"
[type]="'profile'"
></vr-savefile-dialog>
Why I get a error message:
ERROR TypeError: Cannot read property 'createComponent' of undefined
at FileSaveDialogComponent.ngAfterViewInit
and undefined in line:
console.log(this.target);
Create component is, that returns specific component:
switch (this.type) {
case "profile":
return SaveProfileDialogComponent;
case "project":
return SaveProjectDialogComponent;
}
}
After chatting and seeing your entire code it seems that the container with the child you try to access is not yet generated on screen because of an *ngFor condition, it is important to note that you can only access a child with @viewChild if it is already generated. Happy to help!