I have reactive form like this:
<form *ngIf="people$ | async;" [formGroup]="applicationForm" (ngSubmit)="submitForm()">
<person-form
[parentForm]="applicationForm"
(added)="addPerson()"
(removed)="removePerson($event)">
</person-form>
<button type="submit">Submit</button>
</form>
And an appropriate class
export class FormComponent implements OnInit {
applicationForm: FormGroup;
people$: Observable<any>;
constructor( public peopleService: PeopleService ) {}
ngOnInit() {
this.applicationForm = this.fb.group({});
this.people$ = this.peopleService.getPeopleData().pipe(
tap(peopleData => {
this.applicationForm.setControl('people', this.fb.array(peopleData || []));
})
);
}
}
Im my ngOnInit I'm getting data from service which gives me array of people and pushing to applicationForm as form Controls. The problem occurs when I pass that applicationForm to nested form in array: Here is the template of nested form:
<div [formGroup]="parentForm">
<div formArrayName="people">
<div *ngFor="let item of people; let i = index;">
<div [formGroupName]="i">
<input type="number" formControlName="age" />
</div>
</div>
</div>
</div>
And a class of nested form
export class BorrowerFormComponent {
@Input() parentForm: FormGroup;
@Output() added: EventEmitter<any> = new EventEmitter<any>();
@Output() removed: EventEmitter<any> = new EventEmitter<any>();
onAdd() {
this.added.emit();
}
onRemove(index) {
this.removed.emit(index);
}
get people() {
return (this.parentForm.get('people') as FormArray).controls;
}
}
I also emit some adding and removing array elements, I omit this to make code shorter So Ii shows me control after long period of time but also I have error:
Cannot find control with path: 'people -> 0 -> age'
Did I miss something? Why it cannot find 'people -> 0 -> age'? This 'age' field is returned from service.
You didn't declare "age" in your formControl
ngOnInit(){
initGroup() {
let rows = this.parentForm.get('people') as FormArray;
rows.push(this.fb.group({
age: [null, Validators.required],
}))
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.