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

Angular中如何触发父div点击事件并排除特定子元素?

解决方案

要实现点击父div触发事件,点击menu子div时不触发父事件,只需在menu元素上添加点击事件并调用$event.stopPropagation()阻止事件冒泡即可:

修改后的组件代码如下:

@Component({
  selector: 'app-root',
  standalone: true,
  template: `
    <div (click)="openAlert()" class="parent">Parent
      <div class="menu" (click)="$event.stopPropagation()">Menu</div>
      <div class="child child-2">Child 2</div>
      <div class="child child-3">Child 3</div>
    </div>
  `,
})
export class App {
  name = 'Angular';

  public openAlert() {
    alert('Details View');
  }
}

原理说明

  • 浏览器事件默认会向上冒泡,子元素的点击事件会传递到父元素
  • $event.stopPropagation()方法会终止事件传播,阻止事件冒泡到父元素,点击menu时就不会触发父div的openAlert()方法

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 17:03:13