'Reactive Form patchpatch value error when no value provided

I got this problem that I don't get it. I have a formGroup with few controls, here is a simplified code:

.ts

form = new FormGroup({
   firstName: new FormControl(''),
   lastName: new FormControl('')
})

.html

<input type="text" formControlName="firstName" />
<input type="text" formControlName="lastName" /> 

So, when I get the request back from the API, I only have this:

{ 
 firstName: "Johny"
}

Which is fine, the request is correct because in this case Johny didn't provide his last name.

I'm using patchValue to fill the form with the data I received from the API, the problem is that I get this error:

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

Which is correct, I'm not providing that value, but is there a way around it? Or my only options is to always create the object first, giving empty string values and then modifying them accordingly?

Thanks guys



Solution 1:[1]

It should be okay to miss some values when using patchValue() as stated here in the docs.

Try using the spread operator when passing an object as a parameter

this.formGroup.patchValue(...myObj);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nader