我有4个使用loop生成的输入。而且我在UI中使用角度形式,但问题是我只得到最后一个输入值,要求是我需要所有输入值,但前提是我无法生成动态的formControlName。有什么方法可以绕过仅获取最后一个值并获取所有值?
相同的HTML代码是(此循环将基于dataArr执行,这里假设它执行了4次):
<form [formGroup]="dataForm">
<div *ngFor = "let data of dataArr;">
<input type="text" placeholder="Key" value={{data.key}} formControlName="key"/>
</div>
</form>
<button type="button" style="background-color: #4980FF;" (click)="save();">Save</button>
.ts文件中的代码:
// it is initializing and registering the form value
dataForm = new FormGroup({
key: new FormControl('', [Validators.required])
});
save(){
// Here I am trying to print the form value
}
我希望在单击“保存”按钮时获得所有值,而不仅仅是最后一个值。
答案 0 :(得分:0)
您需要改用FormArray
在组件中,创建FormGroup
和FormArray
。
this.dataForm = new FormGroup({
key: new FormArray(this.dataArr.map(data => new FormControl(data.key, [Validators.required])))
// Add other form groups or form controls here
});
save() {
console.log(this.dataForm.value);
}
将这些控件绑定到form
中,如下所示。您不需要value
属性,因为FormControl
会为您绑定值。
<form [formGroup]="dataForm">
<div *ngFor="let data of dataArr; let i = index" formArrayName="key">
<input type="text" placeholder="Key" [formControlName]="i" />
</div>
</form>
<button type="button" style="background-color: #4980FF;" (click)="save();">Save</button>
答案 1 :(得分:0)
在表单中处理项目数组时,您可能需要添加控件或删除控件,甚至编辑现有项目的值,请始终使用有角度的FormArray。
下面是FormArray的有效示例。.这里是有效的Stackblitz 有关FormArray
的更多信息
import {
Component,
OnInit
} from '@angular/core';
import {
FormBuilder,
FormGroup,
FormArray
} from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
name = 'Angular';
dataForm: FormGroup;
items: FormArray;
dataArr: any;
constructor(private formBuilder: FormBuilder) {
}
ngOnInit() {
this.dataForm = this.formBuilder.group({
items: this.formBuilder.array([])
});
setTimeout(() => {
this.dataArr = [{
key: 'First'
},
{
key: 'Second'
},
{
key: 'Third'
},
{
key: 'Fourth'
}
];
this.createItems();
}, 2000)
}
createItems() {
this.items = this.dataForm.get('items') as FormArray;
this.dataArr.forEach((elem: any) => {
const ctrl = this.formBuilder.group({
key: [elem.key]
});
this.items.push(ctrl);
})
}
save() {
console.log(this.dataForm.get('items').value)
return this.dataForm.get('items').value;
}
}
<form [formGroup]="dataForm">
<div formArrayName="items" *ngFor="let item of dataForm.get('items').controls; let i = index;">
<div [formGroupName]="i">
<input type="text" placeholder="Key" formControlName="key" />
</div>
</div>
</form>
<button type="button" style="background-color: #4980FF;" (click)="save();">Save</button>
希望这会有所帮助。