Angular patchValue vs setValue

Tuesday, December 4, 2018

By: Chris Dunn

When creating model driven forms in Angular, for CRUD operations, you will need to map a data model to the FormGroup.  You can do this by manually setting each control value or you can use a function to map the entire data model to the FormGroup model.  At first glance of the documentation it looks like a good option would be setValue on the FormGroup object.

myForm.setValue(formData, {onlySelf: true});

This will work if you have a matching control in the Form Group model (control name) for each value in the data model.  If you don't your code will fail on this error.

FormGroup._throwIfControlMissing

Even though this strict checking serves a valid purpose, and is the safest option, it's not always what we want.  Many times we will only be collecting a portion of the data represented in the data model.  Some strict constructionists would argue that in that case we should use a different view model that only contains the specific view data.  While I don't flatly disagree, sometimes the overhead of more code is not always the best option.  We just need another way to validate the model, which we would want to do anyway.

The Angular team appears to agree in part and so has given us another option, the patchValue function.

myForm.patchValue(formData, {onlySelf: true});

This only sets the values where it can find matching keys, and ignores the other data.  Just be warned that if something is wrong with your model, misspelled key names, no values with be patched.  But at least we have some options.

Tags: angular typescript forms

Copyright 2019 Cidean, LLC. All rights reserved.

Proudly running Umbraco 7. This site is responsive with the help of Foundation 5.