Angular FormGroup vs FormArray




Asked on November 07, 2023
What is difference between FormGroup and FormArray and how to use them?



Replied on November 10, 2023
1. FormGroup tracks the value and validity status of a group of FormControl instances.  FormGroup is used to bind with HTML form.
2. FormArray tracks the value and validity status of an array of FormControl, FormGroup or FormArray instances.
3.  FormArray can be used in the case where we add or delete control at runtime.

4. Example:  FormGroup

form = new FormGroup({
   name: new FormControl('', [Validators.required]),
   age: new FormControl('', [Validators.required])
});

The value and status of  ‘form’ is obtained as
console.log(form.value);
console.log(form.status);

5. Example: FormArray

form = new FormGroup({
   name: new FormControl('', [Validators.required]),
   age: new FormControl('', [Validators.required]),
   friends: new FormArray([
  new FormControl('Mahesh'),
  new FormControl('Krishna')
   ])
});

The value and status of FormArray is obtained as

console.log(form.get('friends').value);
console.log(form.get('friends').status);


Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us