如何在每个代码中使用Angular中的单击功能添加元素?

问题描述 投票:0回答:1

我正在寻找一种在每个打字稿代码的Angular中添加元素的方法。问题是,这些元素应该具有(单击)功能,我不知道应该添加多少个这些元素(例如,具有任意范围的for循环应创建任意数量的元素)。

textausgabe.innerHTML += '<div (click)="caller()"'>click</div>';

这正确地创建了元素,但是如果单击它,什么也不会发生。

您知道一种解决我的问题的方法吗,请告诉我如何:)

angular typescript function onclick innerhtml
1个回答
0
投票

您不应该这样做。在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
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.