Click to watch Angular Playlist: • Angular
To view the code of this tutorial. Please visit this Github link: https://github.com/lets-build-with-co...
Note : Switch the particular branch of the tutorials of Github
To download my git repo of JSON Server & use it in you local for practice, Please visit this link: https://github.com/lets-build-with-co...
Reactive Form | SetValue & PatchValue (How to update form field in TS file)
In Angular's reactive forms, you can use the patchValue and setValue methods to update the values of form controls. Both methods are provided by the FormControl class and have similar functionalities, but with a slight difference.
patchValue method:
Syntax: formControl.patchValue(value, options?)
The patchValue method allows you to update specific form control values without affecting the other controls.
It accepts a JavaScript object or a form control value as the first parameter, representing the new value(s) you want to patch into the form control.
The second parameter, options, is optional and allows you to pass additional configuration options.
Usage example:
typescript
Copy code
formControl.patchValue({ name: 'John', age: 30 });
setValue method:
Syntax: formControl.setValue(value, options?)
The setValue method is used to set the value of a form control, replacing the existing value entirely.
It requires you to provide a value that matches the expected structure and type of the form control.
If you provide an incomplete or incompatible value, it may result in an error.
Usage example:
typescript
Copy code
formControl.setValue({ name: 'John', age: 30 });
The main difference between patchValue and setValue is that patchValue allows you to update specific properties of the form control without affecting the rest, while setValue replaces the entire value.