user33276346
user33276346

Reputation: 1739

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

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>

Upvotes: 5

Views: 7324

Answers (3)

Juan Antonio
Juan Antonio

Reputation: 2614

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.

Upvotes: 0

AVJT82
AVJT82

Reputation: 73357

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

Upvotes: 6

Sagar Kulkarni
Sagar Kulkarni

Reputation: 2081

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[].

Upvotes: 1

Related Questions