将具有自定义angular指令和属性的HTML元素添加到angular Component中



这是一个函数,我正在使用它动态添加一个带有额外HTML元素的组件。在哪个元素中,我试图添加角度自定义指令&属性。但它不起作用(

addComponent(component:any){
let componentRef = this.componentFactoryResolver
.resolveComponentFactory(component)
.create(this.injector);
this.appRef.attachView(componentRef.hostView);
const domElem = (componentRef.hostView as EmbeddedViewRef<any>)
.rootNodes[0] as HTMLElement;
var newcontent = document.createElement('div');
newcontent.innerHTML = `<h1 myDirective [myAttr]="myVar" myAttr2="myVar2">${this.demoText}</h1>`;
domElem.appendChild(newcontent);
document.getElementById("testid").appendChild(domElem);
}

在这里myDirective是一个自定义角度指令。myAttr、myAttr2是自定义角度指令的属性。myVar、myVar2可以是相同组件的静态文本或变量。

在Angular中更改innerHTML不是一个好主意。您必须创建一个指令,在该指令中引入Renderer2的实例来渲染所需的组件。请阅读以下文章=>https://alligator.io/angular/using-renderer2/当做Michael

最新更新