首页 > 解决方案 > ngfor 如何在 Angular 8 中设置动态函数?

问题描述

我的 html 组件中有这个:

<div>
    <button (click)="myFunction1()">myFunction1</button>
</div>
<div>
    <button (click)="myFunction2()">myFunction2</button>
</div>
<div>
    <button (click)="myFunction3()">myFunction3</button>
</div>

在打字稿中:

myFunction1()
myFunction2()
myFunction3()

但我尝试做这样的事情,但它不工作!

打字稿组件:

var myFunctions = [
"myFunction1",
"myFunction2",
"myFunction3"
]

html组件:

<div *ngFor="let myFunction of myFunctions">
    <button (click)="myFunction()">{{myFunction }}</button>
</div>

知道有人有什么解决办法吗?

标签: javascriptangulartypescript

解决方案


您是否希望在单击按钮时执行该功能?只需使用数组来保存对函数的引用。

// *.ts
const myFunctions = [
  myFunction1,
  myFunction2,
  myFunction3
]

然后在您的模板中,您可以将点击事件绑定到该函数。

// *.html
<div *ngFor="let myFunction of myFunctions">
    <button (click)="myFunction()">myFunction</button>
</div>

您上面的示例只是将单击绑定到字符串。


推荐阅读