[英]Ionic3 - How to update value of dynamic ngModel?
我正在使用ionic 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>
誰能想到?
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>
我試着像上面的例子一樣做,但是需要進行如下改進。
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.