muffin
muffin

Reputation: 2104

Ionic Angular : Triggering checkbox from card click

I'm using ionic3 - angular4 or just angular.

I have several card elements that I loop through to display a list of items. Inside each card is a checkbox to indicate whether that item is selected or not.

My problem is, I cannot bind the card to the checkbox state, I want to be able to call the same function when I click the card or I click the checkbox itself (the checkbox sort of kinda only works as an indicator, but all the same I need to attach the select event to it).

By default I don't have the

(click)="selectPack(pack)"

When i attach it to the card-content, the function is called, but the checkbox state doesn't change.

<ion-card color="light" *ngFor="let pack of tmpPackages" icon-left>
<ion-card-content style="float:left;width:100%" (click)="selectPack(pack)">
    <ion-checkbox style="width:35px" color="dark" (ionChange)="selectPack(pack)" [(ngModel)]="pack.selected">
    </ion-checkbox>
    {{pack.label}}  
</ion-card-content>
</ion-card>

Am I doing something wrong? I'm basically just calling the same function when the user is touching the card itself, or the checkbox.

Upvotes: 1

Views: 2683

Answers (2)

sebaferreras
sebaferreras

Reputation: 44659

First, please notice that you need to wrap the ion-checkbox inside of an ion-item so the checkbox will change its state also when clicking in the label next to it.

You can achieve what you're looking for by binding the click event of the ion-card to only change the checkbox value:

(click)="pack.selected = !pack.selected"

and then use the ionChange event of the checkbox to call your method:

(ionChange)="select(pack)"

That way your method is going to be called both if you click the card, or the checkbox (if you click the card, it will change the checkbox, and then that change will call your method).

This would be the end result:

<ion-card color="light" *ngFor="let pack of tmpPackages" icon-left>
  <ion-card-content style="float:left;width:100%" (click)="pack.selected = !pack.selected">

      <ion-item style="background: transparent;">
        <ion-label>{{pack.label}} </ion-label>
        <ion-checkbox color="dark" (ionChange)="select(pack)" [(ngModel)]="pack.selected"></ion-checkbox>
      </ion-item>

  </ion-card-content>
</ion-card>

Also please take a look at this working plunker.

Upvotes: 3

Nguyen Huynh
Nguyen Huynh

Reputation: 533

You should add another parameter i.e source in function selectPack(pack, source). The source will determine which one is click, If card => pack.selected = !pack.selected.

Or just write another function for card click and change pack.selected = !pack.selected. I hope it will automatically trigger the ionChange event on your check box.

Hope this help.

Upvotes: 0

Related Questions