Select only one check box

百般思念 提交于 2020-01-04 07:53:41

问题


I am using ionic 2 and angular 2 for a small project. and I want the user to be able to only select one checkbox from the ones provided. I added and action listener whenever a checkbox is checked but not sure on what the function should really execute.

    <ion-item *ngFor="let category of categories; let i = index">
      <ion-label [innerHTML]="category.name"></ion-label>
      <ion-checkbox color="royal" checked="category.value" (click)="Selection(i,categories);"></ion-checkbox>
  </ion-item>

Here is the sample of the JSON object

    categories = [
    {
      name: 'Car Keys',
      value: 'false'
  },
  {
      name: 'Phone',
      value: 'false'
  },
  {
      name: 'ID/Drivers License',
      value: 'false'
  },
  {   name: 'Wallet',
      value: 'false'
  },
  {   name: 'Other',
      value: 'false'
  }]

I am passing the index of the categories into the function but not sure what else to check for. Any help would be appreciated.


回答1:


This could easiest be achieved using radio buttons, but if you want to use checkboxes, this would mean you should disable the other checkboxes when one is chosen.

The array you have, change the value property to a boolean value false instead, which we can work with. Then when a checkbox is chosen, it would invoke your Selection-function, which sets the other checkboxes' value to to true when one is chosen, keeping the one chosen as false. When user unchecks checkbox, all checkboxes values are again false. To this we use the unique name property, which is passed to the function and when we iterate the categories to see which one is checked. So your function:

Selection(name: string) {
   this.categories.forEach(x => {
       if(x.name !== name) {
           x.value = !x.value
       }
   })
}

And to your template, add the disabled option:

<ion-item *ngFor="let category of categories; let i = index">
  <ion-label>{{category.name}}</ion-label>
  <ion-checkbox [disabled]="categories[i].value" (click)="Selection(category.name);"></ion-checkbox>
</ion-item>

Plunker



来源:https://stackoverflow.com/questions/42879446/select-only-one-check-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!