Search code examples
angularcomponents

Cannot read property 'createComponent' of undefined in ngAfterViewInit


I've been trying to create a dynamic component loader example to proof out some ideas, however I've been completely unsuccessful in getting it to work. I've followed the Angular documentation to a T and even explored solutions here on SO. Nothing has given me any progress yet and I'm not sure where to go from here.

When running the code, I get the error "Cannot read property 'createComponent' of undefined at ParentComponent.ngAfterViewInit"

I'm using Angular 8 if that matters, but as far as I can tell this is sound, yet I can never get my component to display. Thoughts?

Below is my code:

parent.component.ts

export class ParentComponent implements AfterViewInit {
    @ViewChild('ref', { static: true, read: ViewContainerRef }) ref: ViewContainerRef;

    constructor(
        private componentFactoryResolver: ComponentFactoryResolver
    ) { }

    ngAfterViewInit(): void {
        const factory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
        this.ref.createComponent(factory);
    }
}

parent.component.html

    <div fxFlex="grow" fxLayout="column" ngClass="scroll">
        <ng-template ref></ng-template>
    </div>

Solution

  • When defining a template reference variable, make sure that the variable name is preceded by the hash symbol #. In the present case, the template syntax would be:

    <ng-template #ref></ng-template>