2
votes

i am using Ionic 2. I have a radio-group (to change language) :

 <ion-list radio-group >
  <ion-item *ngFor="let language of languages">
    <ion-label>{{language.name}}</ion-label>
    <ion-radio id="language.id" (ionSelect)='showConfirmAlert(language.id)' [checked]="isLanguageSelected(language.id)" [value]="language.name"></ion-radio>
  </ion-item>
</ion-list>

On selecting item (click on radio button), item is automatically changed and checked. But i need to show an confirm alert, then, if user cancels, to cancel item selection and return to initial checked item.

The "checked" attribute is binded with my code

isLanguageSelected(lang){
  let answer = (lang === this.actualLanguage) ? true : false;
  return answer;
}

 chooseLanguage(lang){
     this.actualLanguage = lang;
     this.appGlobals.set('actualLanguage', this.actualLanguage);
}

It works on first arrival on page, but if i launch again , for example to choose english :

this.chooseLanguage('en') ;

this.actualLanguage is well changed to "en" if i log it, and this.isLanguageSelected('en'); returns true, but "checked" value of en-item is not binded to it, and item is not updated.

Is there a way to update item checked attribute from code, and not only from click on radio button ?

thanks !

UPDATE WITH ANSWER :

Finally i resolved this by using [(ngModel)] variable and switching some elements in my code (removing ionSelect, changing binded variable for value...)

<ion-list radio-group [(ngModel)]="selectedLanguage" (ionChange)="onChange()" >
  <ion-list-header>
    Choisissez la langue {{actualLanguage.id}} 
  </ion-list-header>
  <ion-item *ngFor="let language of languages">
     <ion-label>{{language.name}}</ion-label>
    <ion-radio  id="language.id" (click)='showConfirmAlert(language.id)'  [value]="language.id"></ion-radio>
  </ion-item>
</ion-list>
1
define variable: boolean and bind with <ion-toggle [(ngModel)]="variable"></ion-toggle>, then you can set the variable from code.. let me know if works and i will add to answer :) - mosca90
Thanks @mosca90, i finally resolved my problem in adding [(ngModel)] variable, as you suggest. I will update my post. thanks ! - David Anquetin
I added the answer so you can accept and close this questions! @David Anquetin - mosca90

1 Answers

1
votes

In your .ts page:

  1. Define a boolean variable: checkedRadio: boolean
  2. Bind the variable to your component: <ion-radio [(ngModel)]="checkedRadio"></ion-radio>

Now you can set the value from code like this.checkedRadio = false or this.checkedRadio = true

I hope to have been a help to you. :)