我正在使用离子3框架。如何更改ngModel的值?我想以编程方式切换所有离子切换。
组件:
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>
任何人都有主意吗?
答案 0 :(得分:1)
ion-toggle需要一个布尔值,如果将其绑定到一个布尔值,它将起作用。 在allRecs模型属性中,字符串是字符串,因此初始值不会影响ion-toggle,也无法更改它。因此x.model应该为boolean或为值添加一个新的boolean属性以将其设置为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;
}
}
在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>
答案 1 :(得分:0)
我试图像上面的例子那样做,但是需要进行如下改进。
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;
}
}
}
在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>