简体   繁体   English

Angular 获取选中的复选框值返回未定义

[英]Angular get checked checkbox value return undefined

I am using angular with ionic but i can't validate checked items.我正在将 angular 与离子一起使用,但我无法验证检查的项目。

HTML: 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.您没有发送是否选中,您只是发送 id。 Just send your all object and use it.只需发送您所有的 object 并使用它。

In the HTML:在 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);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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