当用户单击按钮时,我将执行以下方法。
@ViewChild("privs") privs: ElementRef;
addPrivs() {
this.privs.nativeElement
.insertAdjacentHTML('beforeend', '<generic1>yey!</generic1>');
}
我的标记如下所示。
<generic1>woosh</generic1>
<div #privs></div>
名为generic1的子组件是这样声明的,当然,它存在于模块的导入中。
import { Component } from "@angular/core";
@Component({
selector: "generic1",
template: "<div>mamba...</div>"
})
export class Generic1 { }
我得到的行为是标记中统计创建的行为按预期显示。动态附加的则不然。根据我调查的 DOM,添加了一个标签 generic1 但它不是由 Angular 渲染的(我看到了文本 yey! 和标签,但没有看到组件的渲染)。
我错过了什么?
我已经在谷歌上搜索了示例,但没有发现我的设置有任何具体错误。一定是超出了我的范围...
最佳答案
您实际上并没有创建动态组件。您正在插入 Angular 未渲染的附加 HTML。当将 Html 和文本插入到这样的模板中时,它们会被清理,因此您不会获得渲染的组件。
This answer对设置动态组件有非常详细的解释。但是,它不是满足您需要的复制和粘贴解决方案。 documentation on Angular.io有一个动态组件加载器的好例子。本质上,您需要一个 ComponentFactoryResolver 来解析和构建 Angular 组件。在 Angular.io 文档的示例中,真正的魔力发生在这个函数中:
loadComponent() {
this.currentAddIndex = (this.currentAddIndex + 1) % this.ads.length;
let adItem = this.ads[this.currentAddIndex];
let componentFactory = this._componentFactoryResolver.resolveComponentFactory(adItem.component);
let viewContainerRef = this.adHost.viewContainerRef;
viewContainerRef.clear();
let componentRef = viewContainerRef.createComponent(componentFactory);
(<AdComponent>componentRef.instance).data = adItem.data;
}
它从 this.ads
中存储的组件列表中检索组件,使用 componentFactoryResolver
解析和构建该组件。它检索 viewContainerRef
并在其上创建组件。
希望能帮助您指明正确的方向。
关于javascript - 动态添加的 Angular2 组件不会渲染,但静态添加的组件会渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42998805/