Angular patchValue vs setValue and dates

169 Views Asked by At

Is there any significant difference between using patchValue or setValue to set the value on a form ? Also is there any difference or best practice regarding using moment or date obj ?

     if(startDate) {
        const date = moment(startDate).toDate();
        this.form?.patchValue({ startDate: date });
      }

      if(endDate) {
        const date = new Date(endDate);
        this.form.get('endDate').setValue(date);
      }

Either way it works as expected for me , so I am just wondering .

2

There are 2 best solutions below

0
MGX On BEST ANSWER

Moment is a matter of preference, you don't NEED it but you can sure use it.

As for patch VS set, the difference is mainly on form groups rather than form controls : setValue requires all fields to be set, but patchValue accepts a partial of all the fields that are expected.

0
sparsh610 On

we use patchValue if we need to update a single value in object or complete object, but we use setvalue when we have to update the object and not single value.