Is there a simple way to unselect a ion-radio in Ionic 2?
Asked Answered
L

3

5

After the user select an ion-radio a function is called at the component. I need that function to unselect the radio.

THE TEMPLATE:

  <form [formGroup]="myForm">
    <ion-list radio-group formControlName="listOptions">
      <ion-item>
        <ion-label>Option 1</ion-label>
        <ion-radio value="1" (ionSelect)="myFunction($event)"></ion-radio>
      </ion-item>
    </ion-list>
  </form>
Lancewood answered 20/4, 2017 at 17:24 Comment(0)
F
6

Not sure about the usecase here, but here we go...

Since you are using a reactive form, you have some functions you can execute on form controls, one of them is reset(). So in your function, you would just reset the value like so:

myFunction() {
  this.myForm.controls.listOptions.reset()
}

and it will reset it to unchecked, if that is your initial state of the radio button.

Demo, which sets resets radio button after a couple of seconds

Fisken answered 20/4, 2017 at 20:55 Comment(2)
You are the bossLancewood
:D Glad I could help! :)Fisken
S
1

You can use checked for that. And use a boolean value to manipulate it. In .html add this

<ion-radio checked={{isChecked}} value="1" (ionSelect)="myFunction($event)"></ion-radio>

In .ts add this:

export class SomePage{
  isChecked = false;

  constructor(...){...}

  myFunction($event){
    this.isChecked = !this.isChecked; // I am assuming you want to switch between checking and unchecking while clicking on radio.
  }

If multiple radio buttons, you can use array of flags like isChecked[].

Sawfly answered 20/4, 2017 at 18:56 Comment(3)
Sadly that solution is not working, the ion-radio remains checked.Lancewood
Try setting it to false manually then. Like this.isChecked = false. Does this work?Sawfly
I get a console error that reads: Can't bind to 'checked' since it is not a known property of 'ion-radio'.Stipulation
D
0

I found some problems doing that with Ionic 4 and I solved this in two differents ways, depends of 4.x version.

view

<ion-item>
  <ion-label> A </ion-label>
  <ion-radio
    (click)="changeA()"
    [checked]=a
  >
  </ion-radio>
</ion-item>


<ion-item>
  <ion-label> B </ion-label>
  <ion-radio
    (click)="changeB()"
    [checked]=b
  >
  </ion-radio>
</ion-item>

<ion-button (click)="remove()">
  <ion-label>
    CLEAN
  </ion-label>
</ion-button>

controller

a = false;
b = false;

changeA(){
  this.a = !this.a
  if(this.a && this.b)
    this.b = false;
}
changeB(){
  this.b = !this.b
  if (this.b && this.a)
    this.a = false;
}

remove(){
  this.a = false;
  this.b = false;
}

If you found some problems, move click from ion-radio to ion-item in each radio button. In an example with 4.11.x. I had to do it but I don't know exactly why.

You can play with an example here.

I hope it help somebody.

Demented answered 10/4, 2020 at 8:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.