SigGP
SigGP

Reputation: 786

Angular - how handle click event inside other clickable container

I have a clickable div which on click navigates to other page. Inside this div I'd like to have a like-component. If user clicks the like then onLikeClicked() should be executed but onContainerClick() should be blocked. Clicking somewhere else inside container should execute onContainerClick(). How can I block onContainerClick() event if user clicks directly on like component?

<div class="container" (click)="onContainerClick()">
    <like (click)="onLikeClicked()">
        
    </like>
</div>

Upvotes: 7

Views: 9596

Answers (3)

Korbinian Kuhn
Korbinian Kuhn

Reputation: 796

You have to stop the event propagation. This not angular specific, just basic javascript. As the official documentation for stopImmediatePropagation() states:

Invoking this method prevents event from reaching any registered event listeners after the current one finishes running and, when dispatched in a tree, also prevents event from reaching any other objects.

component.html

<div class="container" (click)="onContainerClick()">
    <like (click)="onLikeClicked($event)">
        
    </like>
</div>

component.ts

export class Component {

  onContainerClick(): void {
    // do something
  }

  onLikeClicked(event: MouseEvent): void {
    event.stopImmediatePropagation();
    // do something
  }
}

Upvotes: 4

Barremian
Barremian

Reputation: 31135

You could call the stopPropagation() function in the like element's click event to stop the event bubbling.

Try the following

Controller

export class AppComponent  {
  onContainerClick(event) {
    event.stopPropagation();           // <-- also if you want to stop container click event bubbling
    console.log("container clicked");
  }

  onLikeClicked(event) {
    event.stopPropagation();
    console.log('like clicked');
  }
}

Template

<div (click)="onContainerClick($event)" class="container">
  <p (click)="onLikeClicked($event)" class="content">Something inside</p>
</div>

Working example: Stackblitz

Upvotes: 7

MD10
MD10

Reputation: 1531

You can stop the propogation of the event by using event.stopPropagation();

pass the $event to onLikeClicked like this:

    <like (click)="onLikeClicked($event)">
    </like>

then in the function you can call event.stopPropagation();

https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

Upvotes: 11

Related Questions