简体   繁体   中英

Angular get checked checkbox value return undefined

I am using angular with ionic but i can't validate checked items.

HTML:

<div *ngIf="phones.length > 0">
  <ion-item *ngFor="let phone of phones">
    <ion-label>{{phone.name}}</ion-label>
    <ion-checkbox color="dark" (ionChange)="selectMember(phone.id)" [(ngModel)]="phone.isChecked"></ion-checkbox>
  </ion-item>
</div>

Script:

selectedArray: any = []; // should be array of selected items

selectMember(data, isChecked: boolean) {
  console.log(isChecked); //undefined
  if (isChecked === true) {
    this.selectedArray.push(data);
  } else {
    let index = this.selectedArray(data);
    this.selectedArray.splice(index, 1);
  }
  console.log(this.selectedArray);
}

Any idea?

You aren't sending if is checked or not, you're just sending the id. Just send your all object and use it.

In the HTML:

<div *ngIf="phones.length > 0">
  <ion-item *ngFor="let phone of phones">
    <ion-label>{{phone.name}}</ion-label>
    <ion-checkbox color="dark" (ionChange)="selectMember(phone)" [(ngModel)]="phone.isChecked"></ion-checkbox>
  </ion-item>
</div>

In the component:

selectedArray :any = []; // should be array of selected items
selectMember(data) {
    console.log(data.isChecked); //undefined
    if (data.isChecked === true) {
      this.selectedArray.push(data.id);
    }
    else {
      let index = this.selectedArray.indexOf(data.id);
      this.selectedArray.splice(index, 1);
    }
    console.log(this.selectedArray);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM