如何获取单击的垫按钮而不是垫按钮包装器的 ID?

How to get the id of clicked mat-button instead of mat-button wrapper?

我在我的 Angular7 中使用 material 设计 project.There 是垫子上的点击事件-按钮。

  itemclick(event: Event) {
 //to know the id of clicked element,ie button
 let elementId: string = (event.target as Element).id;
 console.log(elementId);
 }

这里是 HTML

<button mat-button color="primary" id="test1" (click)="itemclick($event)" style="outline: none">Property1</button>

但我并不总是得到 id,因为 (event.target) 在 mat-button(id=test1 的情况)和 mat-button-wrapper(id 为 null 的情况)之间不断变化).

如何解决这个问题? 提前致谢。

将您的函数替换为:

HTML:

<button mat-button #test color="primary" id="test1" (click)="itemclick(test)" style="outline: none">Property1</button>

TS:

itemclick(event) {
   console.log(event._elementRef.nativeElement.id)
}

StackBlitz