我正在尝试将组件动态添加到我的应用程序中。
我有一个名为表单容器的组件。我想根据配置在此组件中加载不同的表单。
所以我在谷歌上搜索并尝试动态添加组件,但我收到控制台错误。无法读取属性创建未定义的组件。 this.includeTemplate
未定义。根据代码错误是正确的,因为值没有分配给变量。但是我所指的例子做了同样的事情,这是有效的。
我想我错过了一些东西。
表单容器组件
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
}
}
激活帐户组件
import { Component} from '@angular/core';
@Component({
selector: 'activate-account',
template: `<div class="ActivateAccountContainer"> HI </div>`
})
export class ActivateAccountComponent {
constructor() {}
}
着陆显示.html
<div id="FormContainer" #includeTemplate class="FormContainer ideolveloginform"></div>
正如
@MohamedAliRACHID所说,ngAfterViewInit
使用而不是ngOnInit
,注释中提到的错误通过将动态组件代码封装到函数中来解决setTimeout
。
这是表单容器组件
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);
}
}