【问题标题】:Dynamically create radio buttons based on a dynamic form in Angular基于Angular中的动态表单动态创建单选按钮
【发布时间】:2019-07-31 05:18:27
【问题描述】:

我正在创建一个基于数据集构建的动态响应式表单:例如我有一个对象列表:

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

对于这些对象中的每一个,我想创建一个FormGroup(我有),并基于totalMarks 字段使用无线电输入。

我面临的问题是单选按钮输入本身是动态的,因此我从i = 0; i < totalMarks; i++ 开始迭代totalMarks,例如:

<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>

我创建了一个管道将整数从totalMarks 转换为一个数组。我在这里测试并且工作正常:

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

但显然以上假设totalMarks 是静态的。当我遍历totalMarks 时,如何让模板“看到”这些值?目前,当我在遍历数据集时创建单选按钮时,我会像下面一样传入总分,但这没有任何作用。

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

【问题讨论】:

  • 不知道是不是只有我,但问题还是不清楚。也许您可以使用 stackblitz 创建一个演示?

标签: angular ngfor


【解决方案1】:

您可以查看以下示例以使用 *ngFor 创建多个单选按钮

HTML 文件

<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}}

组件文件

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-13
    • 1970-01-01
    • 2011-01-01
    • 2013-02-03
    • 1970-01-01
    • 2011-07-28
    • 2018-03-25
    • 1970-01-01
    相关资源
    最近更新 更多