【问题标题】:Add HTML elements with custom angular directive and attribute into Angular Component将具有自定义角度指令和属性的 HTML 元素添加到 Angular 组件中
【发布时间】:2018-10-30 12:57:45
【问题描述】:

这里是函数,我用来动态添加带有额外 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 是一个自定义 Angular 指令。 myAttr, myAttr2 是自定义 Angular 指令的属性。 myVar、myVar2 可以是静态文本,也可以是同一个组件的变量。

【问题讨论】:

    标签: javascript html angular typescript


    【解决方案1】:

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

    【讨论】:

    • 我们可以在运行时使用 Renderer2 向元素添加角度指令吗?
    • 不,显然你不能。你找到解决办法了吗?谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2020-11-28
    • 1970-01-01
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多