Search code examples
angularangular-reactive-formsformbuilder

What is the proper way to loop radio button formControl in angular?


I fetch a questionnaire API which contains an array of questions and inside every question I have an array of choices. Here is an example of the json:

{ questions: 
       [ 
          {
             question: "", 
             choices: 
                [ 
                   { 
                      choice: "A", 
                      selected: false 
                    } 
                 ] 
           } 
       ]
}

For this example I'm using ReactiveForms.

Below is a basic structure of how I built the FormGroup. This will be filled depending on how many data I receive from the API.

this.questionnaire = this.formbuilder.group({
     question: this.formbuilder.array([
        this.formbuilder.group({
           question: "data_from_api"
           choices: this.formbuilder.array([
              this.formbuilder.group({
                 choice: "data_from_api",
                 selected: false
              })
           ])
        })
     ])
});


My logic to this, is to loop every question control then loop every choices control inside the question. The problem that I'm facing is that when I loop the choices control array the radio buttons aren't grouped, so it allows the user to select all the choices inside the question.

Here is a how I have my HTML.

<form [formGroup]="questionnaire">
  <div formArrayName="questions">
    <div *ngFor="let question of questionnaire.get('questions').controls; let i = index" [formGroup]="question">
      {{ question.get('question').value }}
      <div formArrayName="choices">
        <div *ngFor="let choice of questions.get('choices').controls; let j = index" [formGroup]="choice">
         <label>
           <input formControlName="selected" type="radio" [value]="true || false">
           {{ choice.get('choice').value }}
         </label>
        </div>
      </div>
    </div>
  </div>
</form>

If radio button (choice) is selected then formControlName="selected" will save as true. I can display without a problem, it works find when I use it with checkboxes.

I tried adding a "name" attribute but doesn't work as you can only have a "formControlName" and "name" with the same value, which in this case you wouldn't want that because that will group all existing radio buttons.

Assuming I can't change the json how can I solve this problem? Can you recommand me some options or links to a similar example. Thank you in advance!


Solution

  • If I'm understanding that correctly, you would need to use i and concatenate that with a custom name for your choices, let's say <input formControlName="selected" [attr.name]="'choice-group-' + i" type="radio" [value]="true || false">, that would create isolated groups per question.