Reputation: 5075
I am using ionic 3 framework. How to change value of ngModel? I want to toggle all ion-toggle programmatically.
component:
allRecs:any;
constructor(){
this.allRecs = [
{
label: "label 1",
model : "model1"
},
{
label: "label 2",
model : "model2"
},
{
label: "label 3",
model : "model3"
}
]
}
public toggle(flag:boolean){
console.log(flag);
}
html:
<ion-item *ngFor="let x of allRecs">
<ion-label> {{x.label}} </ion-label>
<ion-toggle [(ngModel)]="x.model" (ionChange)="toggle(x.model)" item-end>
</ion-toggle>
</ion-item>
Can anyone has idea?
Upvotes: 0
Views: 1052
Reputation: 71
I tried to do like the example above, but needs some improvement like follows.
constructor(){
this.allRecs = [
{
id: 1, //add this line
label: "label 1",
value: false
},
{
id: 2, //add this line
label: "label 2",
value: false
},
{
id: 3, //add this line
label: "label 3",
value: true
}
]
}
/*
* in this method added new parameter `id: number`
*/
toggle(id: number, flag:boolean) {
for(let i=0;i<this.allRecs.length;i++) {
//check if the current record has the same id
if (this.allRecs[i].id == id) {
this.allRecs[i].value = flag;
}
}
}
in html:
<!-- added new parameter `x.id` when occurs `ionChange` event calling toggle method -->
<ion-item *ngFor="let x of allRecs">
<ion-label> {{x.label}} </ion-label>
<ion-toggle [(ngModel)]="x.value" (ionChange)="toggle(x.id, x.value)" item-end>
</ion-toggle>
</ion-item>
Upvotes: 0
Reputation: 11982
ion-toggle needs a boolean value, if you bind it to a boolean, it will work. in your allRecs model attribute is string so initial value not effects on ion-toggle and can't change it. so x.model should be boolean or add a new boolean attribute for e.g value to set it for ngModel:
constructor(){
this.allRecs = [
{
label: "label 1",
value: false
},
{
label: "label 2",
value: false
},
{
label: "label 3",
value: true
}
]
}
toggle(flag:boolean){
for(let i=0;i<this.allRecs.length;i++){
this.allRecs[i].value = flag;
}
}
in html:
<ion-item *ngFor="let x of allRecs">
<ion-label> {{x.label}} </ion-label>
<ion-toggle [(ngModel)]="x.value" (ionChange)="toggle(x.value)" item-end>
</ion-toggle>
</ion-item>
Upvotes: 1