Add hidden fields to a Form with Angular Formly

Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 9 months ago

Sometimes you need add values to your form without having a visible UI form control. A typical example is the id property of your data model. With Formly you actually have multiple choices. By default Formly has a 2-way databinding between the form and the data model. As a result you can directly use the model and send it back to the server as it will be always in sync with the form. If you decide to still use the form value, check out this lesson to see how to implement "hidden fields".

Instructor: [00:00] One thing that is very comfortable about Formly is that data binds also the model value. For instance, in a form where we have multiple properties but we only map a subset of them, we can actually use the model to send them that dollar properties back to the server again.

[00:16] For instance, assume that we loaded the model from the server and we probably have some primary key here. Usually, the primary key is not part of my form values because I don't create a form control for that primary key and visualize it on a form.

[00:32] Rather, what I usually do is I bind default controls I want to change, for instance first name, age and so on, and my model is always up to date. Whenever I change the nation, you can see the nation here gets data bound immediately. In that way, I always have to enter model and I can directly send it back to the server on the onSubmit event.

[00:53] A different approach is to place the ID also in the form value and then use the form value to post back to the server. This can be easily achieved by directly going to the fields configuration and create a so-called hidden field. The only thing I'm binding here is the actual ID property. I don't specify any type or template options because that field should not be visible.

[01:16] If I change that and save it, and if I go now to my form value, you can see that the actual ID gets data bound, but it is not visible here on that form directly.