我正在使用角度反应形式,并且具有如下形式的结构。
{
"name": '',
"params": {}
}
我想在params formGroup中添加动态属性(表单控件)。下面是我使用的代码,但它给出了空的controls
对象。
ts文件
exercise = {
data:[
{param: "Reps"},
{param: "Tempo"}
],
};
{
this.exerciseForm = this.formBuilder.group({
name: ['', [Validators.required],
params: this.formBuilder.group({})
});
}
get getAllParams(){
return this.exerciseForm.get('params') as FormGroup;
}
addNewParam(){
this.getAllParams[param] = this.formBuilder.control('');
}
模板文件
<div formGroupName="params" *ngFor="let param of exercise.data;">
<input type="text" [formControlName]="param.param" />
</div>
有人可以帮助我创建相同的结构吗?
答案 0 :(得分:1)
//At first only "name" and a formGroup "params" empty
this.exerciseForm = this.formBuilder.group({
name: ["", [Validators.required]],
params: this.formBuilder.group({})
});
this.exercise.data.forEach(param => {
(this.exerciseForm.get("params") as FormGroup).addControl(
param.param,
new FormControl()
);
});
请参阅stackblitz
已更新 :. html之类的
<form [formGroup]="exerciseForm">
<input formControlName="name">
<div formGroupName="params">
<div *ngFor="let param of this.exercise.data">
<input [formControlName]="param.param">
</div>
</div>
</form>
<pre>
{{exerciseForm?.value|json }}
</pre>
*更新2 以避免错误 我们可以在输入中添加一个* ngIf
<input *ngIf="exerciseForm.get('params.'+param.param)"
[formControlName]="param.param">
另一个方法是使用键盘值来循环控制
<form [formGroup]="exerciseForm2">
<input formControlName="name">
<div formGroupName="params">
<div *ngFor="let control of exerciseForm2.get('params').controls|keyvalue;let i=index">
<input [formControl]="control.value">
</div>
</div>
</form>