我正在尝试动态添加组件到我的应用程序。
我有一个名为 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>
答案 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);
}
}