Angular 2在单击子项时防止单击父项 [英] Angular 2 prevent click on parent when clicked on child

查看:31
本文介绍了Angular 2在单击子项时防止单击父项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套一级的点击事件.当我单击子项时,会调用预期的函数,但也会调用父项的函数.这是代码

I have a click event nested one level. When i click on the child the expected function is called but the parent's function is also called. Here is the code

<li class="task-item" *ngFor="let task of tasks" (click)="showTask(task.name)">
    <input type="checkbox" [ngModel]="task.taskStatus" (ngModelChange)="changeTaskStatus($event)" />
</li>

所以当复选框改变时 changeTaskStatus()showTask() 一起调用.我希望父母在复选框更改时保持安静.我如何实现这一目标?在 Angular 1 中很容易处理这个

So when the checkbox changes changeTaskStatus() and the showTask() called together. I want the parent to keep quiet when checkbox changes. How do I achieve this? It was easy to handle this in Angular 1

我尝试过但失败的事情

在复选框的点击事件中使用了 $event.stopPropagation() 没有任何改变

Used $event.stopPropagation() in the checkbox's click event that changed nothing

<input type="checkbox" [ngModel]="task.taskStatus" (click)="$event.stopPropagation()" (ngModelChange)="changeTaskStatus($event)" />

推荐答案

checkbox事件需要使用stopPropagation():

You need to use stopPropagation() for checkbox event:

<input type="checkbox" [ngModel]="task.taskStatus" (ngModelChange)="changeTaskStatus($event);$event.stopPropagation()" />

它可以防止当前事件在捕获和冒泡阶段进一步传播.您可以在此处阅读更多内容.此外,您可能需要将 stopPropagation() 添加到复选框的 click 事件中,但我不是 100% 确定:

It prevents further propagation of the current event in the capturing and bubbling phases. You can read more here. Also, you probably need to add stopPropagation() to click event of checkbox, but I'm not 100% sure:

<input type="checkbox" [ngModel]="task.taskStatus" (click)="$event.stopPropagation()" (ngModelChange)="changeTaskStatus($event)" />

这篇关于Angular 2在单击子项时防止单击父项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆