Select only 1 radio button with Ionic

Asked

Viewed 917 times

1

I’m trying to render some radio buttons using *ngFor and only that I can select or first or the last option, never the middle options.

I got the following array:

[
   {
     "title": "First question",
     "options": [
       {
         "title": "Title 1",
          "correct": 0
        },
        {
         "title": "Title 2",
          "correct": 0
        },
        {
         "title": "Title 3",
          "correct": 0
        },
        {
         "title": "Title 4",
          "correct": 1
        },
     ]
   }
]

<ion-card *ngFor="let question of questions">
  <ion-card-content>
    <form>
      {{ question.title }}
      <ion-list radio-group>

        <ion-item *ngFor="let option of question.options">
          <ion-label>{{ option.title }}</ion-label>
          <ion-radio [value]="option.correct"></ion-radio>
        </ion-item>

      </ion-list>

      <button ion-button secondary full>Next question</button>
    </form>
  </ion-card-content>
</ion-card>

In the above example, even if it renders all radio buttons I can only select the Title 1 or the Title 4

  • Isn’t it because the value is equal in the first 3? They should have different value. Do a test by placing a different value for each.

  • yes @Andrévicente, tested and really is the same value, but would that be an "error" of the right framework? because for a radio to be considered "unique" the name is that it should be compared...

  • 1

    I took a look at the documentation https://ionicframework.com/docs/api/components/radio/RadioButton/ , it seems you do not have the property name. I’m not sure if it’s a bug, I’d have to go deeper to find out, but it seems that when we use ion-radio Ionic doesn’t create a common input type="radio", so it doesn’t behave the same. Good luck

2 answers

1

In this case you will need to put the ion-radio group in a radio-group:

 <ion-list radio-group>
        <ion-item *ngFor="let item of items">
          <ion-label>{{item.cond}}</ion-label>
          <ion-radio [value]="item.host" (click)="inserirCondominio(item)"></ion-radio>
        </ion-item>
      </ion-list>

-1

Specify the input element as radio.

 <input type="radio" name="unique_value_or_id" value="unique_value_or_id"/>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.