Gem*_*Gem 7 angular-material angular angular-reactive-forms angular-forms angular8
我正在使用 Angular8 和反应式形式。我的 ngOnInit 是:
ngOnInit(): void {
this.makeForm = this.fb.group(
year: ['', Validators.required],
amount: ['', Validators.required],
desc: ['', Validators.required],
details: new FormArray([
this.det(),
]
);
}
det() {
return new FormGroup({
for: new FormControl(''),
remarks: new FormControl('')
});
}
Run Code Online (Sandbox Code Playgroud)
我有来自后端的数据来修补数组:
{
"amount": 9000,
"year": 1996,
"id": 1,
"desc": "P1",
"details": [
{
"id": 1,
"remarks": "ok",
"for": "1"
},
{
"id": 24,
"remarks": "OK",
"for": "1"
},
{
"id": 25,
"remarks": "OK",
"for": "1"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我通常用这种方法修补值:
getppredit() {
let data:any = this.shareService.ParentShare.value;
let id = data.id;
this.dataService.getdataEdit(id)
.subscribe((result: any) => {
let no = result.no;
let year = result.year;
this.makeForm.patchValue({
no: no,
year: year
});
});
}
Run Code Online (Sandbox Code Playgroud)
上面的代码用于普通修补,但是如何使用 Angular8 的响应式形式动态修补数组内部的值呢?
在这里尝试一下这个
getppredit(){
let data:any = this.shareService.ParentShare.value
let id = data.id
this.dataService.getdataEdit(id)
.subscribe((result: any) => {
let no = result.no;
let year= result.year
this.makeForm.patchValue({
no : no,
year: year
})
//initialize empty array
this.getFormArray() = new FormArray([]);
//create needed formGroups and inside each formGroup all formControls
for (let detail of result.details) {
let idControl: FormControl = new FormControl('');
let requestForControl: FormControl = new FormControl('');
let remarkControl: FormControl = new FormControl('');
idControl.setValue(detail.id);
ForControl.setValue(detail.requestFor);
remarkControl.setValue(detail.remark);
this.getFormArray().push(new FormGroup({
id: idControl,
For: requestForControl,
remark: remarkControl}));
}
})//end of subscribe
}
getFormArray(): FormArray{
return this.makeForm.get('details') as FormArray;
}
Run Code Online (Sandbox Code Playgroud)
表单数组通常旨在包含动态数据。因此,您必须首先在表单数组内创建动态表单控件(在收到响应后),然后将值放入其中。
| 归档时间: |
|
| 查看次数: |
17378 次 |
| 最近记录: |