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
相关产品推荐
相关产品推荐

