角反应形式绑定不起作用 [英] Angular reactive form binding not working
问题描述
我正在尝试在此处创建嵌套的反应形式: https://stackblitz.com/edit/angular-mgrfbj
I'm trying to create nested reactive forms here : https://stackblitz.com/edit/angular-mgrfbj
这是项目层次结构:
---create company form (hello.component.ts)
--- company details form (company-details.component.ts)
--- [
employee details form (employee-details.component.ts)
employee details form
employee details form ...
]
对于这种嵌套形式,我必须使用此视频中给出的ViewProviders
和FormGroupDirective
:
For such nested forms, I have to use ViewProviders
and FormGroupDirective
as given in this video:
第一个嵌套表单( company-details.component.ts )可以正常工作
The first nested form (company-details.component.ts) is working as expected
但是在FormArray
中添加了*ngFor
的第二种形式未正确绑定到FormGroupDirective
.
But the second form which is added with *ngFor
inside a FormArray
is not binding to the FormGroupDirective
correctly.
当您键入公司详细信息并按 Print Json 时,打印的json将是正确的.但是,当您添加一两个员工时,该员工的详细信息不会打印在json中.
When you type the company details and press Print Json, then the printed json will be correct. But when you add an employee or two, then the employee details are not printed in the json.
我知道还有其他手动方法可以完成同一件事,但是我正在寻找一种干净的解决方案,该解决方案无需任何额外功能即可工作.
I know there are other manual ways to accomplish the same thing, but I'm looking for a clean solution that just works without any extra functions.
任何帮助将不胜感激!
预先感谢
推荐答案
您需要对代码进行一些更改
there are to make several changes in your code
1.-employee.details.component.html
1.-The employed.details.component.html
<!---see that is [formGroup], not formGroupName-->
<div [formGroup]="employee">
<h4 class="row">Employee no. {{index+1}}</h4>
<div class='col-md-8'>
<input formControlName="name" placeholder="Name">
</div>
<div class='col-md-8'>
<input formControlName="planet" placeholder="Planet">
</div>
</div>
2.-被雇用的.details.component.ts,变为
2.- the employed.details.component.ts, becomes as
employee: any;
@Input() index;
//inject the ForumGroupDirective in the variable fgd
constructor(private fb: FormBuilder,
private fgd: FormGroupDirective) {}
ngOnInit() {
//get the FormArray of "employees"
const array=(this.fgd.form.get('employees') as FormArray);
//Simple push to the array
array.push(this.fb.group({
name: '',
planet: ''
}));
//the formGroup must be array.at(index)
this.employee = array.at(this.index)
}
最后,在删除员工时,必须删除数组中的元素
Finally, when remove the employe you must remove the element in the array
removeEmployee() {
this.employeesCount -= 1;
(this.form.get('employees') as FormArray).removeAt(this.employeesCount);
}
请参见 stackblitz
这篇关于角反应形式绑定不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!