简体   繁体   English

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

[英]Add HTML elements with custom angular directive and attribute into Angular Component

Here is the function, I'm using to add a component dynamically with additional HTML elements. 这是函数,我用来动态添加带有其他HTML元素的组件。 In which element I'm trying to add Angular Custom Directive & Attributes. 我正在尝试在哪个元素中添加Angular自定义指令和属性。 And it is not working. 而且它不起作用。 :( :(

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);
}

Here myDirective is a Custom Angular Directive. 此处myDirective是自定义角度指令。 myAttr, myAttr2 are Attributes of the Custom Angular Directive. myAttr,myAttr2是自定义角度指令的属性。 myVar, myVar2 are may static text or variables of the same component. myVar,myVar2可以是相同组件的静态文本或变量。

changing the innerHTML in Angular is not a good Idea. 在Angular中更改innerHTML不是一个好主意。 You have to create a directive where you bring in an instance of Renderer2 to render the components you need. 您必须创建一个指令,在其中引入Renderer2实例以呈现所需的组件。 Please read the following Article => https://alligator.io/angular/using-renderer2/ Regards Michael 请阅读以下文章=> https://alligator.io/angular/using-renderer2/关于 Michael

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM