Home Angular Tutorials Angular setValue and patchValue methods

Angular setValue and patchValue methods

by aouidane.med.amine
75,052 views 20 min read

In this tutorial we are going to see how to use setValue and patchvalue methods to set up the model values using the reactive forms approach using a real life example.

When we use the reactive forms concept , we will have access to setvalue and patchvalue methods provided by the AngularFormsModule.

setValue and patchValue could be used with multiple control types. 

it could be used with a simple formControl ,formGroup or formArray.

Table of Contents

SetValue and patchValue Methods

SetValue Method

setValue method used to update the values of the control.

When we use this method with formGroup or formArray control , the object structure in the parameter must be the same as the control structure otherwise it will throw an error.

Syntax :

setValue(value: { [key: string]: any; }, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void

formControl SetValue

let’s try to create a simple formControl model and set the value using setValue method  :

				
					  initializeForm(): void {
    this.tagsForm = this.formBuilder.group({
      webSite: new FormControl('', Validators.required),
    });
  }
  
    setFormControlValue(): void {
    const website = 'XperTuto';
    this.tagsForm.get('webSite')?.setValue(website);
  }
				
			

formGroup SetValue

In the previous example we have seen how to use setValue in a simple formControl , now we will use the same concept and use the method in formGroup control.

So to prevent errors , we need to pass the same object structure as the formGroup structure in the setValue method parameter.

				
					  initializeForm(): void {
    this.tagsForm = this.formBuilder.group({
      webSite: new FormControl('', Validators.required),
      tags: this.formBuilder.array([
        this.formBuilder.group({
          technology: '',
          nb_tutorials: '',
        })
      ]),
    });
  }
  
  
  setFormGroupValue(): void {
    const tagsFormGroupValues = {
      webSite: 'www.XperTuto.com',
      tags: [
        {
          technology: 'Angular',
          nb_tutorials: '100',
        },
        {
          technology: 'NodeJs',
          nb_tutorials: '100',
        }
      ]
    }

    this.tagsForm.setValue(tagsFormGroupValues);
  }
				
			

As you see we have passed the same object structure as the formGroup .

Now what will happen if we pass a different structure by removing the webSite control for example ?

we will get an error like this :  

angular setValue and patchValue error

formArray SetValue

In the previous example we have seen how to use setValue in formGroup , now we will use the same concept and use the method in formArray control.

				
					  setFormArrayValue(): void {
    const tagsFormArrayValues = [
      {
        technology: 'Typescript',
        nb_tutorials: '200',
      }
    ]

    this.tagsForm.get('tags')?.setValue(tagsFormArrayValues);
  }
				
			

PatchValue Method

patchValue method used also to update the control values but using a different concept.

we don’t need to pass the same object structure as the Control , the method accepts any structure and updates only the part which matches the control structure.

Syntax :

patchValue(value: { [key: string]: any; }, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void

formControl PatchValue

let’s start by using the the patchValue method in a simple formControl :

				
					  patchFormControlValue(): void {
    const website = 'XperTuto';
    this.tagsForm.get('webSite')?.patchValue(website);
  }
				
			

formGroup PatchValue

In this example we are going to use the patchValue in formGroup without respecting the formGroup structure to prove that patchValue is still working even if the object structure is totally different to the control structure by removing the “webSite” property.

				
					  patchFormGroupValue(): void {
    const tagsFormGroupValues = {
      tags: [
        {
          technology: 'Angular',
          nb_tutorials: '100',
        }
      ]
    }
    
    this.tagsForm.patchValue(tagsFormGroupValues);
  }
				
			

formArray PatchValue

Now we will use the patchValue method in formArray control without respecting the formArray structure by removing the first object property  from the model : “technology”

				
					
  patchFormArrayValue(): void {
    const tagsFormArrayValues = [
      {
        nb_tutorials: '200',
      }
    ]

    this.tagsForm.get('tags')?.patchValue(tagsFormArrayValues);
  }
				
			

onlySelf option

When we use setValue or patchValue , it is required to pass the object in the parameter , but also we have some interesting options to use such as onlySelf and emitEvent.

onlySelf option is used when we need to bypass the default behavior of the form validation.

when angular detects any changes in the form values , it checks the validation of the complete form but in same cases we need to check only the validation of the current control.

To do that we just need to add the onlySelf option in the parameter of the setValue and patchValue method.

Syntax :

patchValue(value: { [key: string]: any; }, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void

emitEvent option

By default , angular forms emit two different events . it emits the valuesChanges when angular detects any changes in the form values , and also emits the statusChanges every time when angular checks the form validation.

the statusChanges is recommended to be used when we want to detect only the validation changes of the form instead of using the valueChanges to detect every change then we get the form validation manually. 

the statusChange observable return a string value : ‘VALID’ or ‘INVALID’

when we use the setValue and patchValue , we can activate or deactivate the emitEvent option like this :

				
					    this.tagsForm.get('tags')?.patchValue(modelValues,
    {onlySelf: false, emitEvent: false});
				
			

References

Clone the Project

To download and run the example, please follow the steps :

1- Clone the source code from XperTuto git repository using the following command : 

git clone https://github.com/www-xperTuto-com/angular_setValue_and_patchValue.git

2- Install the node dependencies using NPM command line  : npm install

3- Run the application using the following command : ng serve 

4- Access to the project through the URL : http://localhost:4200 

Read More About Angular Forms :

Recapitulation

In this tutorial we have seen how to use setValue and patchValue methods through an example to see the difference between them to be able to use the right method depending on the use case.

We have also seen  how to use these methods with different types of angular control such as simple formControl , formGroup and formArray.

We have also seen the options provided by these methods that allows us to better control the form validation using the onlySelf and emitEvent options.

I hope you enjoy reading this Tutorial.

You may also like