我只是新手。当用户添加教育领域时,它具有使用添加和删除行创建多个教育的功能。为此,我使用了FormArray。 它可以正确获取数据,但是会创建一个额外的嵌套表单。
`
/file.ts file
// inside constructor
constructor() {
this.educationinfo = this.form.group({
education: this.form.array([this.educationform(this.education) ])
});
}
// inside ngOnInit
ngOnInit() {
this.route.params.subscribe(params => {
this.id = params.id;
this.service.getProfilebyId(this.id).subscribe(res => {
this.users = res;
this.users.eduacation = res['education'];
// tslint:disable-next-line:prefer-const
for (let education of this.users.eduacation) {
this.addEducation(education);
}
public educationform(education) {
if (!education) {
education = {
institutionName: '',
level: '',
yearGraduated: '',
board: '',
faculty: ''
};
}
return new FormGroup({
institutionName: new FormControl(education.institutionName),
level: new FormControl(education.level),
yearGraduated: new FormControl(education.yearGraduated),
board: new FormControl(education.board),
faculty: new FormControl(education.faculty),
});
}
addEducation(education): void {
this.education = this.educationinfo.get('education') as FormArray;
this.education.push(this.educationform(education));
}
/file.html
<form [formGroup]="educationinfo" style="padding: 0px 0px 100px 0px!important;">
<ng-template matStepLabel>Educational Information</ng-template>
<div formArrayName="education" *ngFor="let education of educationinfo.get('education')['controls']; let i= index;">
<div [formGroupName]="i">
-------</div>
</div>
</form>
`
我希望输出与数组的长度匹配,但实际上,它会创建一个额外的嵌套形式。
答案 0 :(得分:0)
如注释中所述,您正在constructor
中创建一个空的表单组,因此这就是“额外”表单组的原因。最初不要创建一个空的表单组,只需创建一个空的表单数组即可:
constructor(private form: FormBuilder) {
this.educationinfo = this.form.group({
education: this.form.array([])
});
}