【发布时间】:2020-03-27 20:32:34
【问题描述】:
我想创建一个动态数量的 html dom 元素按钮,并让它们能够在单击时调用服务。有什么办法吗?
例如test.component.ts:
import {ApiService } from '../services/api.service';
...
export class test implement OnInit(){
constructor(private apiGet : ApiService) { }
ngOnInit() {
...
for (i = 0; i < x; i++) {
var row = document.getElementById('row');
var cell = insertCell();
cell.innerHTML = "<button name='" + i + '" (click)=test.callService()>click me</button>";
}
}
public callService() {
//call ApiService here using buttons name
}
}
当我将 (click) 事件放在 test.component.html 内的 html 元素上时,我一直在让它工作,但它对 dom 生成的按钮不起作用。有什么我遗漏的,还是有更好的方法来做到这一点?
【问题讨论】:
-
要动态生成元素,请考虑使用*ngFor
标签: angular typescript dom