Ionic3 - How to update value of dynamic ngModel?

你离开我真会死。 提交于 2019-12-13 20:16:52

问题


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?


回答1:


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>



回答2:


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>


来源:https://stackoverflow.com/questions/55558029/ionic3-how-to-update-value-of-dynamic-ngmodel

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