【问题标题】:Call the component dynamically angular2, attaching customElement to DOM onClick动态调用组件 angular 2,将自定义 Element 附加到 DOM onClick
【发布时间】:2017-02-07 06:05:31
【问题描述】:

我正在尝试将元素附加到父 DOM onClick。如何动态调用组件? 如果我添加简单的“hello world”,它会按预期工作。但我想调用“myCustomTag”组件。

注意:如果我直接在模板中添加“myCustomTag 标签”,它会起作用。它按预期附加了“myCustomTag”模板。

     @Component({
      selector: 'myTag',
      template: `<div (click) = "onAttachClick()"> clickToAddELement </div>`
    })
    export class xxx {
     getNewElement() {
         return '<myCustomTag [name]="someText"></myCustomTag>'
        }
        //on click, I need to add the element
        onAttachClick() {
       this.parentElement.insertAdjacentHTML('beforeend',this.getNewElement());
        }
}

【问题讨论】:

    标签: angular angular2-template


    【解决方案1】:

    你可以在

    中设置一个局部变量
    <div #myAttach (click) = "onAttachClick()"> clickToAddELement </div>
    

    并使用

    export class xxx {
       @ViewChild('myAttach') myAttach;
       ....
    }
    

    然后

    this.myAttach.nativeElement.insertAdjacentHTML('beforeend',this.getNewElement());
    

    阅读本文可能会对您有所帮助: What's the proper way of accessing native element in angular2 (2 diff ways) docs are scarce

    【讨论】:

    • 嗨,大卫,感谢您的回复。附加一个元素很好..但我无法调用“mycustamtag”组件..它将空的html元素附加到父级。一些我想用 html 调用“mycomponent”的方式
    • @Dns 啊,我明白了。你能告诉我你是如何实现 的吗?
    猜你喜欢
    • 2016-04-23
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2017-03-02
    • 2023-03-25
    相关资源
    最近更新 更多