You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中点击按钮后,如何从event获取父级button元素?

如何在Angular中获取mat-icon-button的父级button元素?

这里有几种简单直接的解决方案:

方案1:使用event.currentTarget

currentTarget始终指向绑定了事件的元素(也就是你的mat-icon-button对应的button),和实际点击的子元素无关,这是最直接的方法:

download(event: MouseEvent) {
  const buttonElement = event.currentTarget as HTMLButtonElement;
  // 现在buttonElement就是你需要的父级button元素
}

方案2:用closest()向上查找DOM元素

从点击的mat-icon元素出发,向上遍历DOM树,找到最近的button元素(可以加上类名更精准匹配):

download(event: MouseEvent) {
  const buttonElement = (event.target as HTMLElement).closest('button.mat-icon-button') as HTMLButtonElement;
  if (buttonElement) {
    // 这里可以处理button元素的逻辑
  }
}

方案3:模板引用变量(更Angular风格)

直接在模板里给button添加引用变量,点击时直接传递这个元素到方法里,完全不需要操作事件对象:

模板代码:

<button mat-icon-button #downloadButton (click)="download(downloadButton)">
  <mat-icon>download</mat-icon>
</button>

TS代码:

download(buttonElement: HTMLButtonElement) {
  // 直接拿到目标button元素
}

内容的提问来源于stack exchange,提问作者Doppu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 15:09:49