如何从 Ionic 中的多个复选框中获取所有值

How can I get all values from multiple checkboxes in Ionic

我有一个应用程序,为此页面我使用了复选框。我想从用户那里获得更多选择。当我点击按钮时,我想看到所有选中的选项。

我的 .html 代码

 <ion-item *ngFor="let item of durumozellikleri">
        <ion-label>{{item.ozellik}}</ion-label>
        <ion-checkbox [(ngModel)]="durumozellik"></ion-checkbox>
 </ion-item>

 <button ion-button (click)="getAll()">Click Me</button>

我的 .ts 代码

 let headers: any = new HttpHeaders({ 'Content-Type':'application/json' }),
 options: any = { "key": "kontrol", "id": this.id},
 url: any = 'http://207.180.202.55/MisKebap/php/durumozellikgetir.php';


 this.http.post(url, JSON.stringify(options), headers)
 .map(res => res.json())
 .subscribe(res => {

   this.durumozellikleri = res;
 })

您可以向 durumozellikleri 中的项目添加一个字段,并使用该字段存储复选框值,如下所示;

  durumozellikleri = [
    { ozellik: "ozellik1", secim: false },
    { ozellik: "ozellik2", secim: false },
    { ozellik: "ozellik3", secim: false },
  ]

在html

<ion-item *ngFor="let item of durumozellikleri">
    <ion-label>{{item.ozellik}}</ion-label>
    <ion-checkbox [(ngModel)]="item.secim"></ion-checkbox>
 </ion-item>

这里有一个简单的演示https://stackblitz.com/edit/angular-u6ecgk

您可以尝试对 component.ts 和 component.html 进行以下更改。

在您的 component.html 上,您必须将 durumozellikleri 数组中每个元素的选中值绑定到 ngModel.

<ion-item *ngFor="let item of durumozellikleri">
  <ion-label>{{item.ozellik}}</ion-label>
  <ion-checkbox [(ngModel)]="item.checked"></ion-checkbox>
</ion-item>

<button ion-button (click)="getAll()">Click Me</button>

关于你的 component.ts,我不确定 durumozellikleri 的确切结构,但你应该在每个对象中添加一个名为 checked 的额外 属性 durumozellikleri。要仅获取选中的选项,您可以使用 Array.filter()。

this.durumozellikleri=[
  {ozellik : '123', checked : false},
  {ozellik : '234', checked : false},
  {ozellik : '214', checked : false},
];

getAll() {
  console.log(this.durumozellikleri);
  const res = this.durumozellikleri.filter(obj => obj.checked);
  console.log(res)
  // do the rest here
}

这是一个有效的 demo