Reputation: 203
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.
Upvotes: 2
Views: 3982
Reputation: 73357
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>
Upvotes: 2