How to Set a Reactive Form Value in Angular?

There are two ways to set a reactive form value in Angular. First, using the setValue() method and second using the patchValue() method.

To understand the working of both methods, let’s first create a reactive form that has three fields firstName, lastName, and age of the student:

// Create a form
this.form = this.formBuilder.group({
  'firstName': ['', Validators.required],
  'lastName': ['', Validators.required],
  'age': ['', Validators.required]
});

To set the value of this form using the setValue() method you have to pass an object containing each of the form control names along with the values you want to set in the form.

So, in our case, we have to pass an object that has the keys firstName, lastName and age:

setFormValues() {    

  this.form.setValue({
    firstName: 'John',
    lastName: 'Doe',
    age: '25'
  });

  // Add other stuff
}

The problem with the setValue() method is that you have to pass each and every form control value. If any of the form control is missing, the compiler will throw you an error.

For example, if you do not pass the age field value in the setValue() method, you will get the following error:

ERROR Error: NG01002: Must supply a value for form control with name: 'age'

Set Form Value using the patchValue() Method

The pathValue() method solves the above problem. This method does not restrict you to pass all the form control values.

It’s up to you how many form control values you want to set. You can set only one, two, three or all the form controls values if you want.

For example, if now you only pass the firstName and lastName form control values and do not pass any value for the age field, the compiler will not throw you any errors:

setFormValues() {  
    
  this.form.patchValue({
    firstName: 'John',
    lastName: 'Doe',
  });

  // Add other stuff
}

The patchValue() method in the above example will set only the firstName and lastName fields’ values. The age field value will remain as it is.