我试图在动态创建的元素上绑定事件。我很成功,但我无法将该函数绑定到事件。这是我的代码
.ts代码
data = ['fn1()', 'fn2()', 'fn3()'];
fn1() { alert(1) }
fn2() { alert(2) }
fn3() { alert(3) }
HTML代码
table>
<ng-container *ngFor='let d of data'>
<tr (click)=d>
<td>
:) !!!
</td>
</tr>
</ng-container>
但是,当我静态添加函数然后它被调用,即。
<table>
<ng-container *ngFor='let d of data'>
<tr (click)=fn1()>
<td>
:) !!!
</td>
</tr>
</ng-container>
</table>
这项工作,任何人都可以帮助我吗?
你想要一个函数数组,而不是一个字符串数组。并且您希望在单击div时调用该函数:
打字稿:
fn1 = () => { alert(1) };
fn2 = () => { alert(2) };
fn3 = () => { alert(3) };
data = [this.fn1, this.fn2, this.fn3];
HTML:
<div (click)="d()">