Angular 2 prevent click on parent when clicked on child

后端 未结 3 773
北海茫月
北海茫月 2021-02-02 06:42

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

<         


        
相关标签:
3条回答
  • 2021-02-02 06:54

    You need to use stopPropagation() for checkbox event:

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

    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)" />
    
    0 讨论(0)
  • 2021-02-02 07:01

    Just you need to add $event.stopPropagation() code on Child div on click event

     <input  (click)="onChildClickFunction();$event.stopPropagation()"/>
    
    0 讨论(0)
  • 2021-02-02 07:11

    This is known as Event Bubbling. Events are first handled by the innermost element and then propagate to the outer elements until they reach the root.

    <div *ngFor="let item of userList">
      <div (click)="setUserData(item)">
        <a (click)="getUserDetails(item.user.id)">Name - {{item.user.name}}</a>
      </div>
    </div>
    

    In this case, when you click on username or tag, it will first call inner element i.e. getUserDetails() and the root element i.e. setUserData().

    So, to prevent this event bubbling, just add

    event.preventDefault();

    in defination of getUserDetails($event) or

    <a (click)="getUserDetails(item.user.id); $event.stopPropagation();">Name - {{item.user.name}}</a>
    

    That's all you need to you.

    0 讨论(0)
提交回复
热议问题