问题描述
我正在创建基于数据集构建的动态反应形式:例如我有一个对象列表:
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}, ...]
对于每个对象,我想基于 totalMarks
字段创建一个带有无线电输入的 FormGroup
.
For each of these objects, I want to create a FormGroup
(which I have) with a radio input based on the totalMarks
field.
我面临的问题是单选按钮输入本身是动态的,因此我从 i = 0开始遍历totalMarks;我<totalMarks;i ++
,例如:
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>
我创建了一个管道,用于将整数从 totalMarks
转换为数组.我在这里测试并正常工作:
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>
但是显然,以上假设 totalMarks
是静态的.当我遍历 totalMarks
时,如何获取模板以查看"值?当前,当我遍历数据集时创建单选按钮时,我将如下所示传递总标记,但这无济于事.
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)
});
}
推荐答案
您可以检查以下示例,使用* ngFor
You can check below example to create multiple radio buttons with *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);
}
}
这篇关于基于Angular中的动态表单动态创建单选按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!