Angular 2防止在单击子级时单击父级 [英] Angular 2 prevent click on parent when clicked on child
问题描述
我有一个嵌套在一个级别中的点击事件.当我单击子级时,将调用预期的功能,但还调用父级的功能.这是代码
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)" />
推荐答案
您需要对复选框事件使用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屋!