如何在 Angular 中通过事件获取按钮的父元素

在 angular 中处理按钮点击事件时,若需从子元素(如 mat-icon)反向获取其父级 button 元素,应使用 `event.target.parentnode`,而非 `event.target` 本身——因为事件实际触发于子元素,需向上遍历 dom 树定位目标父节点。

在你提供的 HTML 结构中:

点击行为实际由 触发(因其位于按钮内部且可交互),因此 event.target 指向的是 元素,而非外层

download(event: MouseEvent) {
  const parentButton = event.target?.parentNode as HTMLElement;
  console.log('Parent button:', parentButton);
}

推荐写法(增强健壮性)
为避免 event.target 为 null 或 parentNode 不存在导致运行时错误,建议添加类型守卫和空值检查:

download(event: MouseEvent) {
  const target = event.target as HTMLElement | null;
  const parentButton = target?.parentNode as HTMLButtonElement | null;

  if (parentButton && parentButton.tagName === 'BUTTON') {
    console.log('Found parent button:', parentButton);
    // 可进一步调用原生方法,例如 parentButton.click() 或读取属性
  } else {
    console.warn('Parent element is not a button or unavailable');
  }
}

⚠️ 注意事项

  • 不要使用 event.currentTarget 替代 parentNode —— currentTarget 指向绑定事件监听器的元素(即