Angular setValue and patchValue methods

How to update HTML elements on a form with new data.

  • Use setValue() to update all form controls
  • Use patchValue() to update a sub-set of form controls
  • We can use patchValue() to update all the form controls

why we need to update HTML elements on a form with new data.

Let’s say, we are using the form below to edit an existing employee. To be able to edit an existing employee details we have to retrieve data from a server and then update the form controls on the form with that retrieved data.

This can be very easily achieved using setValue() method.

onLoadDataClick(): void {
     this.employeeForm.setValue({
      fullname: "John smith",
       email: "john@abc.com",
       skills: {
         skillName: "Nodejs",
         totalexperience: 10,
         proficiency: 'beginner'
     }
   });

when “Load Data” button is clicked, the form controls are updated with the form model data specified in onLoadDataClick() event handler.

Updating only a sub-set of HTML elements on the form : If I want to update only a sub-set of HTML elements on the form, can I still use setValue() method. The answer is NO. Let’s see what happens if I use setValue() method and try to update only fullName and email fields.

If you want to update only a sub-set of form controls, then use patchValue() method instead of setValue().

onLoadDataClick(): void {
    this.employeeForm.patchValue({
    fullname: "John smith",
    email: "john@abc.com"
    // skills: {
    //   skillName: "Nodejs",
    //   totalexperience: 10,
    //   proficiency: 'beginner'
    // }
});

use setValue() to update all form controls and patchValue() to update a sub-set of form controls

Source Download

github

Leave a Reply

Your email address will not be published. Required fields are marked *