无法读取ngAfterViewInit中未定义的属性“ createComponent”

时间:2019-10-30 20:30:13

标签: angular components

我一直在尝试创建一个动态组件加载器示例,以证明一些想法,但是我一直没有成功使其成功。我已经将Angular文档跟踪到了T,甚至在此处探讨了SO上的解决方案。一切还没有给我任何进展,我不确定从这儿去哪里。

运行代码时,出现错误"Cannot read property 'createComponent' of undefined at ParentComponent.ngAfterViewInit"

如果这很重要,我正在使用Angular 8,但据我所知这是声音,但我始终无法显示我的组件。有想法吗?

下面是我的代码:

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>

1 个答案:

答案 0 :(得分:1)

在定义template reference variable时,请确保变量名称前面带有井号#。在当前情况下,模板语法为:

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