Venusssss
Venusssss

Reputation: 528

Difference between .value and .setValue in reactive forms in Angular 7+

I would like to fully understand what are the differences between .value and .setValue in angular 7+ and under which circumstances that are suitable for using .value or .setValue?

Example 1: this.createLocForm.setValue(data);

Example 2: this.data = this.createLocForm.value

Upvotes: 19

Views: 30457

Answers (3)

Pawan Jaiswal
Pawan Jaiswal

Reputation: 21

setValue() will set the value of all form controls of the form group.

patchValue() method will also set Formcontrol values from a model but only for those which we have mentioned in the model. So, it is not necessary to pass all the model info in patchValue() method.

Upvotes: 2

Prashant Pimpale
Prashant Pimpale

Reputation: 10697

They both are completely different:

.setValue() is a function which used to:

Sets the value of the FormGroup. It accepts an object that matches the structure of the group, with control names as keys.

For example:

If you have:

const formGroup = new FormGroup({
  name: new FormControl(),
  mobileNo: new FormControl()
});

then your setValue:

formGroup.setValue({name: 'Prashant', mobileNo: '99XXXXXXXX'});

In case of the below code, it will not work:

formGroup.setValue({full_name: 'Prashant', mobileNumber: '99XXXXXXXX'}); -- The keys are important for set value

or

formGroup.setValue({ name: 'Prashant'}); -- Will not work as it is missing mobileNo key from the specified object

.value is a property:

which used to get/access the value of formGroup.

Upvotes: 2

Ramesh Rajendran
Ramesh Rajendran

Reputation: 38683

Example 1: this.createLocForm.setValue(data);

Use the setValue() method to set a new value for individual control. The setValue() method strictly adheres to the structure of the form group and replaces the entire value for the control. Please read this for more details

Example 2: this.data = this.createLocForm.value

This is a read-only property. You can't assign any value for this property. You can only do read the control values by using this property.

Upvotes: 6

Related Questions