添加动态组件时出错 angular 2

Getting error while adding dynamic component angular 2

我正在尝试将组件动态添加到我的应用程序。

我有一个名为 formcontainer 的组件。我想根据配置在此组件中加载不同的表单。

所以我在 google 上搜索并尝试动态添加组件,但我收到控制台错误。 无法读取 属性 未定义的 createComponent。 this.includeTemplate 未定义。根据代码错误是正确的,因为值没有分配给变量。但是我所指的示例做了同样的事情并且正在工作。

我想我错过了什么。

formcontainer 组件

    import { Component, OnInit, Input, ElementRef, ComponentFactoryResolver, ViewChild, ViewContainerRef} from '@angular/core';
    import { FORM_DIRECTIVES } from '@angular/forms';

    import {ActivateAccountComponent} from  '/thinkshop/widgets2/thinkshopapplication/activateaccount/activateaccount.ts'


    @Component({
        selector: 'form-container',
        templateUrl: '/thinkshop/widgets2/thinkshopapplication/login/template/landingdisplay.html'
    })

    export class FormContainerComponent implements OnInit{

        @ViewChild('includeTemplate', { read: ViewContainerRef })  
        private includeTemplate: ViewContainerRef;
        private componentRef:ComponentRef<any>;

        constructor(private resolver: ComponentFactoryResolver) {}

        ngOnInit() : void{          

            let componentFactory = this.resolver.resolveComponentFactory(ActivateAccountComponent);
            this.componentRef = this.includeTemplate.createComponent(componentFactory);
            // this.includeTemplate is undefined

        }       
    }

ActivateAccountComponent

import { Component} from '@angular/core';

@Component({
    selector: 'activate-account',
    template: `<div class="ActivateAccountContainer"> HI </div>`
})

export class ActivateAccountComponent {

    constructor() {}    
}

landingdisplay.html

<div id="FormContainer" #includeTemplate class="FormContainer ideolveloginform"></div>

正如@MohamedAliRACHID 所说,使用 ngAfterViewInit 而不是 ngOnInit,评论中提到的错误通过将动态组件代码封装到 setTimeout 函数中来解决。

这里是formcontainer组件

import { Component, ElementRef, ComponentFactoryResolver, ViewChild, ViewContainerRef, AfterViewInit} from '@angular/core';
import { FORM_DIRECTIVES } from '@angular/forms';

import {ActivateAccountComponent} from  '/thinkshop/widgets2/thinkshopapplication/activateaccount/activateaccount.ts'


   @Component({
      selector: 'form-container',
      templateUrl: '/thinkshop/widgets2/thinkshopapplication/login/template/landingdisplay.html'
   })

    export class FormContainerComponent implements AfterViewInit{

        @ViewChild('includeTemplate', { read: ViewContainerRef })  
        private includeTemplate: ViewContainerRef;
        private componentRef:ComponentRef<any>;

        constructor(private resolver: ComponentFactoryResolver) {}     

        ngAfterViewInit() : void{

        setTimeout(() => {
            let componentFactory = this.resolver.resolveComponentFactory(ActivateAccountComponent);
            this.componentRef = this.includeTemplate.createComponent(componentFactory);
        }, 1);      
    }       
    }