ANURAG RANJAN
ANURAG RANJAN

Reputation: 135

handling multiple click events , if all are under single div which is clickable

I am working with Angular Project

  1. I have Implemented mat card that is clickable
  2. In that card there are two buttons

eg

<div mat-card (click)='details()'>
   <input placeholder='enter name'>
   <button (click)='submit()> Submit </button>
   <button (click)='cancel()> Cancel </button>

</div>

ts

details(){}
submit(){}
cancel(){}

How to handle all the three function

Upvotes: 3

Views: 1803

Answers (1)

CodeWarrior
CodeWarrior

Reputation: 5176

Since you have set a click listener for your mat-card which in your case is the parent, any children under your parent will also trigger the click event of the parent. You need to stop the parent's click being triggered when the child element is clicked. You have to use $event.stopPropogation in order to achieve that.

html

<mat-card class="example-card" (click)="detail()">
    <mat-card-header>
        <mat-card-title>Title</mat-card-title>
    </mat-card-header>
  <mat-card-content>
    <button (click)="submit();$event.stopPropagation();">Submit</button>
    <button (click)="cancel();$event.stopPropagation();">Cancel</button>
  </mat-card-content>
</mat-card>

ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  submit(){
    console.log('submit');
  }

  cancel(){
    console.log('cancel');
  }

  detail(){
    console.log('detail');
  }
}

Upvotes: 4

Related Questions