如何使用angular 6在HTML元素上绑定动态功能?

时间:2019-03-14 11:06:16

标签: angular angular6 angular-directive dynamic-function

我试图将事件绑定到动态创建的元素上。我非常成功,但是无法将功能绑定到事件。这是我的代码

.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>

这行得通,有人可以帮我吗?

1 个答案:

答案 0 :(得分:4)

您需要一个函数数组,而不是一个字符串数组。您想在单击div时调用该函数:

TypeScript:

fn1 = () => { alert(1) };
fn2 = () => { alert(2) };
fn3 = () => { alert(3) };
data = [this.fn1, this.fn2, this.fn3];

HTML:

<div (click)="d()">

Demo