Dave
Dave

Reputation: 5416

Ionic2 toggle component change event not firing

My app is rendering fine, but why would the change event function updateItem(item) not be firing?

Template:

  <ion-list>
    <ion-item-sliding *ngFor="#item of items">
      <ion-item>
        <ion-label>{{item.title}}</ion-label>
        <ion-toggle [(ngModel)]="item.completed" (change)="updateItem(item)"></ion-toggle>
      </ion-item>
      <ion-item-options>
        <button primary (click)="editItem(item)">
          <ion-icon name="edit"></ion-icon>Edit
        </button>
      <button secondary (click)="deleteItem(item)">
        <ion-icon name="delete"></ion-icon>Delete
      </button>
      </ion-item-options>
    </ion-item-sliding>
  </ion-list>

Class:

export class Todos {
...
  updateItem(item) {
    alert(1)
    this._todosService.update(item).subscribe(
      response => { this.getItems(); }
    );
  }
... 
}

Upvotes: 18

Views: 30109

Answers (3)

Fryck
Fryck

Reputation: 485

According to the Ionic documentation, you can do that :

<ion-toggle [(ngModel)]="item.completed" (ionChange)="updateItem(item)" checked="false"></ion-toggle>

I hope this will help you!

Upvotes: 47

Jaydeep Kataria
Jaydeep Kataria

Reputation: 867

If initial value true then ionChange is not useful because its is trigger every time.

<ion-toggle [(ngModel)]="item.completed" (ngModelChange)="updateItem(item)"></ion-toggle>

Hope this is helpful !

Upvotes: 3

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657516

update

<ion-toggle [(ngModel)]="itemCompleted"></ion-toggle>
export class Todos {
  get itemCompleted() {
    return item.completed;
  }
  set itemCompleted(value) {
    item.completed = value;
    updateItem(item);
  }

  ...
  updateItem(item) {
    alert(1)
    this._todosService.update(item).subscribe(
      response => { this.getItems(); }
    );
  }
  ... 
}

original

When [(ngModel)]="..." works, this

(ngModelChange)="updateItem(item)"

should work as well and probably do what you try to accomplish.

Upvotes: 6

Related Questions