sonEtLumiere
sonEtLumiere

Reputation: 4562

Angular nested ngFor with radio buttons

Hi i'm trying to loop each variant and then assigns a radio-button to each option, the issue i have is that i can only choose one item of total variants, when i'm looking for to get one item of each variant, this is what i tryed with indexes. thanks for your help

let obj = {
  variants: [
    {name: "sauce", options: [{name: "soy", price: 3}, {name: "mayo", price: 1}]},
    {name: "size", options: [{name: "xl", price: 4}, {name: "m", price: 2}]}
  ]
}

<div *ngFor="let variant of obj.variants; index as i">
  <h6>{{variant.name}}</h6>                             
  <div *ngFor="let option of variant.options; index as j">>
     <div class="custom-control custom-radio">
       <input id="option{{i}}{{j}}" type="radio" class="custom-control-input" [value]="option" [(ngModel)]="radioSelected" (change)="setRadioOption(variant, option)">
       <label for="option{{i}}{{j}}" class="custom-control-label">{{option.name}}</label>
     </div>
  </div> 
</div> 

 

Upvotes: 0

Views: 926

Answers (1)

Charmis Varghese
Charmis Varghese

Reputation: 595

You need to group radio buttons by adding name attribute to get the behavior you want.

Your input element would look like:

<input id="option{{i}}{{j}}" type="radio" name="option{{i}}" class="custom-control-input" [value]="option" [(ngModel)]="radioSelected" (change)="setRadioOption(variant, option)">

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/radio

Upvotes: 1

Related Questions