>我在 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的"传统"方式。
你在 Angular2 中这样做的方式,这根本不起作用。Angular 不会处理(解析()
、[]
、{{}}
绑定或实例化组件或指令)以任何方式动态添加的 HTML。
角度方式就像
<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>