我正在寻找一种在每个打字稿代码的Angular中添加元素的方法。问题是,这些元素应该具有(单击)功能,我不知道应该添加多少个这些元素(例如,具有任意范围的for循环应创建任意数量的元素)。
textausgabe.innerHTML += '<div (click)="caller()"'>click</div>';
这正确地创建了元素,但是如果单击它,什么也不会发生。
您知道一种解决我的问题的方法吗,请告诉我如何:)
您不应该这样做。在ts文件中添加一个数组,然后使用*ngFor
在模板中遍历该数组。然后,您可以在(click)
处理程序中将元素添加到该数组。 *ngFor
将负责为您创建该元素。
template.html
<div *ngFor="let element of elements" (click)="caller()">click</div>
<div (click)="appendElement()"></div>
component.ts
@Component({...})
export class MyComponent {
public elements:Array<unknown> = [];
public appendElement():void {
this.elements = [...this.elements, this.elements.length + 1]; // Just append anything, since you are not using the values otherwise, appending a generic ID here
}
public caller():void {
// Do whatever you want when your appended elements are clicked
}
}