0

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

2 Answers 2

1

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,
    }))
  }
Sign up to request clarification or add additional context in comments.

3 Comments

in demo it is working but when I try to use this code in real application it shows an error: ERROR TypeError: Cannot read properties of undefined (reading 'map')
my bad, i get data on click event in real app not oninit!
Now its working fine! Many thanks!
1

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);

3 Comments

I tried to use your code but nothing happens! also No errors!
I guess its ok if I use : const dataFromService: Array<{name: string; label: string}> = this.data form.patchValue({id: this.id, reference: dataFromService })
I agree with you @Edward that using patchValue() would be a good practice! Please give me some idea to get rid of this issue.. if possible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.