Using a radio-list in a form in Ionic 3


#1

Hi! I’m new to Ionic and trying to implement a form where a user can select an item from an array. When they click save I want this item to be pushed to an array in another page.

I’m getting stuck on two things. First - how do I assign the value to each list item so that my form understands what has just been selected? I understand that I should be using some [value] or [ngValue] type thing but am struggling to make this work. Second - how do I grab the actual value from my array to push to the other page?

Here is a snippet of my HTML:

<ion-list radio-group>
    <ion-item *ngFor="let item of itemList">
        <ion-label [formControlName]="item.title">{{item.title}}</ion-label>
        <ion-radio></ion-radio>
    </ion-item>
</ion-list>

<button ion-button full color="primary" (click)="saveItem()">Save Item</button>

And my TypeScript save method:

saveItem(){
    if(this.addItemForm.valid){
      this.badSubmitAttempt = false;
      console.log("success");
      console.log(this.addItemForm.value);
      this.itemProvider.addItem({item: this.addItemForm.value.item.title});
      this.navCtrl.push(itemPage);
    } else {
      this.badSubmitAttempt = true;
    }
  }

I think part of the problem could be how I’ve defined my formBuilder in the constructor, but examples I’ve been using online have been fairly sparse and unhelpful in this regard. How am I supposed to define the “item.title” part within formBuilder.group() when it is dynamically generated by whatever is within the itemList array?

Many thanks! I’ll try to provide better clarification if it is needed.


#2

Here is what you need to do:
1- The variable to hold the selected value needs to be assigned to the radio-group

<ion-list formControlName="selectedItem" radio-group>
</ion-list>

2- Then for every ion-radio item in the list you need to give it a value attribute

<ion-list formControlName="selectedItem" radio-group>
    <ion-item *ngFor="let item of itemList">
        <ion-label>{{item.title}}</ion-label>
        <ion-radio [value]="item.title"></ion-radio>
    </ion-item>
</ion-list>

PS: you might need to use value="{{item.title}}" instead of [value]="item.title"

3- Of course don’t forget to add your variable to the forms builder object

private addItemForm= this.formBuilder.group({
    selectedItem: ['Here you can place a default value to be selected if you want'],
});

4- So every time the user selects a new item from the radio-group the value of this item will be assigned to the variable selectedItem and you can access it like:

console.log(this.addItemForm.value.selectedItem);

I don’t think it really matters where you define your formBuilder (in constructor or in class declarations).
Good Luck ^^