javascript - 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>
知道有人有什么解决办法吗?
解决方案
您是否希望在单击按钮时执行该功能?只需使用数组来保存对函数的引用。
// *.ts
const myFunctions = [
myFunction1,
myFunction2,
myFunction3
]
然后在您的模板中,您可以将点击事件绑定到该函数。
// *.html
<div *ngFor="let myFunction of myFunctions">
<button (click)="myFunction()">myFunction</button>
</div>
您上面的示例只是将单击绑定到字符串。
推荐阅读
- qt - 在 Wayland 下运行 Qt 应用程序
- jquery - 如何在单击或点击时获取 jQuery 以运行相同的功能
- python - sentry POST 数据未传播到 UI
- python - 在 PySpark 中合并两个数据框
- oracle - 00904 创建表时
- git - 为什么 .. 和 ... 的含义在 git diff 和 git log 之间翻转?
- python - 将列表列表随机分成两半
- git - Git - 在从远程拉取之前保留并忽略文件更改
- mysql - 如何在 MYSQL 中插入来自不同数据库的新表值及其匹配 id
- rust - 如何将两个 u8 基元转换为 u16 基元?