Dynamically create radio buttons based on a dynamic form in Angular

怎甘沉沦 提交于 2021-01-29 17:44:13

问题


I'm creating a dynamic reactive form that is built based on a data set: e.g. I have a list of objects:

[{question: 1, totalMarks: 3}, {question: 2, totalMarks: 2}, ...]

For each of these objects, I want to create a FormGroup (which I have) with a radio input based on the totalMarks field.

The problem I face is the radio buttons input itself is dynamic, whereby I iterate over totalMarks starting from i = 0; i < totalMarks; i++, e.g.:

<div class="group">
        <label> <input type="radio" formControlName="radGrp1" value="0">0</label>
        <label> <input type="radio" formControlName="radGrp1" value="1">1</label>
        <label> <input type="radio" formControlName="radGrp1" value="2">2</label>
        <label> <input type="radio" formControlName="radGrp1" value="3">3</label>
</div>
<div class="group">
        <label> <input type="radio" formControlName="radGrp2" value="0">0</label>
        <label> <input type="radio" formControlName="radGrp2" value="1">1</label>
        <label> <input type="radio" formControlName="radGrp2" value="2">2</label>
</div>

I created a pipe to transform the integer from totalMarks into an array. I tested here and worked fine:

<div *ngFor="let mark of totalMark | numberToListPipe">
    <label>
        <input type="radio" *ngFor="let i of mark" value="i">{{i}}
    </label>
</div>

But obviously the above assumes totalMarks to be static. How do I get the template to "see" the values as I iterate over totalMarks? Currently, when I create the radio buttons when iterating over the data set, I pass in the total marks like below, but this does nothing.

createRadioForm(totalMarks){
    return this.fb.group({
        marksScored: new FormControl(totalMarks, Validators.required)
    });
}

回答1:


You can check below example to create multiple radio buttons with *ngFor

Html File

<hello name="{{ name }}"></hello>
<p>
  Start editing to see some magic happen :)
</p>

<div *ngFor="let enum of enum_details">
  <label for="enum_answer_{{enum.name}}">
    <input id="enum_answer_{{enum.name}}" [value]='enum.name' type="radio" name="enums" [(ngModel)]="radioSelected">
    {{enum.name}}
  </label>
</div>
<button (click)='radioFun()'>Checked value in console</button>
{{radioSelected}}

Component File

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
  radioSelected: any;
  enum_details = [
    {name: 'html'},
    {name: 'Css'},
    {name: 'Angular'},
  ]

  radioFun() {
    console.log(this.radioSelected);
  }
}

working example here



来源:https://stackoverflow.com/questions/57283682/dynamically-create-radio-buttons-based-on-a-dynamic-form-in-angular

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!