有几个步骤可以使它工作:
更改表单模板如下:
<form [formGroup]="form">
<app-company-details></app-company-details>
<app-employee-details jsonname="employee1"></app-employee-details>
<app-employee-details jsonname="employee2"></app-employee-details>
</form>
根据提供的jsonname
字符串创建嵌套表单组:
员工详细信息.component.ts
@Component({
selector: 'app-employee-details',
viewProviders: [
{
provide: ControlContainer,
useExisting: FormGroupDirective
}
],
...
})
export class EmployeeDetailsComponent implements OnInit {
@Input() jsonname;
constructor(private fb: FormBuilder, private fgd: FormGroupDirective) { }
ngOnInit() {
const group = this.fb.group({
name: new FormControl(),
planet: new FormControl()
});
this.fgd.form.addControl(this.jsonname, group);
}
}
员工详细信息.component.html
<div [formGroupName]="jsonname">
...
</div>
Stackblitz 示例