[英]Add HTML elements with custom angular directive and attribute into Angular Component
這是函數,我用來動態添加帶有其他HTML元素的組件。 我正在嘗試在哪個元素中添加Angular自定義指令和屬性。 而且它不起作用。 :(
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.