Home > Enterprise >  Best way to bind form array using patchValue in Angular 12 reactive form
Best way to bind form array using patchValue in Angular 12 reactive form

Time:11-26

I am getting data in different format but after using 'split' finally I got the proper value in response. Now the console shows the response data as below:

0:{ name: 'dev', label: 'actor' },
1:{ name: 'madhu', label: 'actress' },
 ......

Now I want to patch these data in my formArray

I have created one demo for better understanding..

DEMO

CodePudding user response:

use patchvalue() as defined in the documentation

// Get the data from the service or a placeholder defined here
const dataFromService: Array<{name: string; label: string}> = [
  { name: 'dev', label: 'actor' },
  { name: 'madhu', label: 'actress' }
];
// patch the form array with your data
// as long as your data conforms to the names of the FormControls in your formArray, patchValue works
form.patchValue(dataFromService);

CodePudding user response:

You need to push formGroup into the formArray, as below. Anytime you want to add data, you can push into the array ( you can use the extension you made to get the form control 'credentials')

 ngOnInit(): void {
    this.form = this.fb.group({
      credentials: this.fb.array(this.getData()),
    });
  }

  getData(): FormGroup[] {
    return this.data.map(d => this.fb.group({
      name: d.name,
      label: d.label,
    }))
  }
  • Related