Angular 2:将组件填充到模板

Angular 2: Populating components to template

我正在 Angular2 RC/Ionic2 尝试用字符串数组中的按钮填充 div,并为添加的每个按钮附加点击处理程序。到目前为止,我在以下方面取得了成功:

onPageLoaded() {
    array.forEach(function (item){
        let element = document.createElement("button");
        element.setAttribute('id', item);
        element.innerHTML = item;
        let container = document.getElementById("button-container");
        container.appendChild(element);
    }
}

在视觉上,一切似乎都运行良好。但是,当我尝试使用以下任一方法附加点击处理程序时:

element.setAttribute('(click)', myFunction());

或者这个:

element.onclick(myFunction());

按钮没有出现。我确实注意到这是将对象引入 DOM 的 "traditional" 方法。有没有 Angular 的方法来做到这一点?

这不是您在 Angular2 中执行此操作的方式,这根本不起作用。 Angular 不处理(解析 ()[]{{}} 绑定或实例化组件或指令)以任何方式动态添加的 HTML。

Angular 方法就像

<div id="button-container">
  <button *ngFor="let item of array" [attr.id]="item" (click)="myFunction(item)">{{item}}</button>
</div>

<div id="button-container"> 不是必需的,我只是添加它,因为它在你的问题中提到了。

我会利用关联的模板来做到这一点,而不是直接在 DOM 上工作(Angular2 会为你做):

<template ngFor [ngForOf]="array" #element>
  <button (click)="myFunction($event)" [innerHTML]="element"></button>
</template>

不一定需要使用脱糖表达式,但取决于您期望的输出。您可以直接使用以下内容:

<button *ngFor="let element of array"
   (click)="myFunction($event)" [innerHTML]="element"></button>

此外,我不知道你在element变量中有什么,但如果它不是HTML,你可以直接使用如下所述的插值:

<button *ngFor="let element of array"
   (click)="myFunction($event)" [attr.id]="element">{{element}}</button>