I am having a reactive form with the dynamic input field. I generated these fields with FormArray
. Now, I am trying to prepopulate the form with data on the edit screen but couldn't able to do. I tried to populate using setControl
method I got this error Cannot find control with path: 'books -> 0 -> name'
These are the sources I took for reference
- https://alligator.io/angular/reactive-forms-formarray-dynamic-fields/
- https://stackoverflow.com/a/44988197/9715025
- https://stackoverflow.com/a/42599327/9715025
Component
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
export interface ServerResponse {
books: any;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
formGroup: FormGroup;
books: FormArray;
constructor(
private http: HttpClient,
private formBuilder: FormBuilder,
) {
}
createForm() {
this.formGroup = this.formBuilder.group({
books: this.formBuilder.array([this.createBookForm()]),
});
}
createBookForm() {
return this.formBuilder.group({
name: [],
author: [],
});
}
addBook() {
this.books = this.formGroup.get('books') as FormArray;
this.books.push(this.createBookForm());
}
getData(): Observable<ServerResponse> {
return this.http.get<ServerResponse>('https://demo0331989.mockable.io/library/data/book');
}
populateData() {
this.getData().subscribe(data => {
this.formGroup.setControl('books', this.formBuilder.array(data.books || []));
});
}
ngOnInit() {
this.createForm();
this.populateData();
}
}
HTML
<form [formGroup]="formGroup">
<div formArrayName="books" *ngFor="let book of formGroup.get('books')['controls']; let i = index;">
<div class="row" [formGroupName]="i">
<input type="text" autocomplete="off" placeholder="*Name"
formControlName="name">
<input type="text" autocomplete="off" placeholder="*Author"
formControlName="author">
<button type="button" class="btn btn-success" (click)="addBook();">Add</button>
</div>
</div>
</form>
I am also sharing the code in Stackblitz. Sample/mock data to be prepopulated. I am not sure what I'm missing here!