添加动态组件角度2时出错

时间:2017-10-23 11:45:06

标签: angular angular-components

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

我有一个名为 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>

1 个答案:

答案 0 :(得分:0)

正如@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);      
    }       
    }
相关问题