Search code examples
angularionic-frameworkdom-eventsstoppropagationevent-propagation

Button click event inside clickable ion-card executes parent event too


I am creating an ionic app that fires a modal when I click on a card, the problem I'm facing is that when I click a button on the card, the modal opens as well, how do I stop this from happening. I am open to any workarounds as I have been stuck on this for awhile. Below is some useful code and pictures:

//html
  <ion-grid>
    <ion-row>
      <ion-col size="6" *ngFor="let item of exercises">
        <ion-card class="exercise-card" (click)="openModal(item.id)">
          <img [src]=item.image class="image-card">
          <h3 style="font-weight: bold;">{{item.name}}</h3>
          <h5>{{item.sets}} sets of {{item.reps}} reps and {{item.remarks}}</h5>
          <h6>{{item.date | date: 'dd/MM/yyyy'}} ({{item.time}})</h6>
          <br>
          <div style="text-align: center;">
            <ion-button size="medium" style="width: 30%;" color="success" (click)="complete(item)">
              <ion-icon slot="icon-only" name="checkmark-outline"></ion-icon>
            </ion-button>
            <ion-button size="medium" type="submit" style="width: 30%;" [routerLink]="['/edit-exercise', item.id]">
              <ion-icon slot="icon-only" name="create-outline"></ion-icon>
            </ion-button>
            <ion-button size="medium" style="width: 30%;" color="danger" (click)="delete(item)">
              <ion-icon slot="icon-only" name="trash-bin"></ion-icon>
            </ion-button>
          </div>
        </ion-card>
      </ion-col>
    </ion-row>
  </ion-grid>

The modal should only fire when : click the cards on this page:

.

But instead it fires when I click the blue edit button as well:

here.


Solution

  • it called event propagation. it means that when you trigger an event all same events of parents will be executed. to prevent that, you can do something like this for example:

    in this tag, when you execute complete() function, pass the $event too:

    <ion-button size="medium" style="width: 30%;" color="success" (click)="complete($event, item)">
    

    in complete() function add this line:

    function complete(event, item) {
    
      //your code
    
      event.stopPropagation();
    }
    

    stopPropagation() prevents the parent click event to be executed.