Ignore div click if click was on button inside div

Viewed 4476

I have a div with a button inside of it that minimizes the div. If you click anywhere else inside the div it will load details about the div. However, I don't want to load details if minimizing the div. Here is my code:

<div (click)="showDetails(key)" *ngFor="let key of keys">
    <button (click)="minimize(key)">Minimize</button>
    <span>The rest of the content is here</span>
</div>

When minimize is triggered, I want to ignore showDetails.

4 Answers

I'm not able to test it right now, but what you could try is

(click)="minimize(key, $event)"

In your component

minimize(key, event) {
  event.preventDefault();
  event.stopPropagation();
}

Try with either one of them and see how it goes !

what you have to do is to ignore the parent click event by stopping the propagation of the event using stopPropagation()

html code :

<div (click)="showDetails(key)" *ngFor="let key of keys">
    <button (click)="minimize(key,$event)">Minimize</button>
    <span>The rest of the content is here</span>
</div>

ts code :

minimize(key,event){
       event.stopPropagation();
}

use event.stopPropagation() to prevent the click event from bubbling up the DOM.

What i did here to get around it pretty simple where you do not need create the function/method.

<div (click)="showDetails(key)" *ngFor="let key of keys">
    <button (click)="$event.stopPropagation()">Minimize</button>
    <span>The rest of the content is here</span>
</div>

Hope this helps!

Related