Dynamically disable a Form field with Angular Formly

Share this video with your friends

Social Share Links

Send Tweet

Ever had to disable a form control based on the value of another form control? If your city dropdown field is filtered based on the current nation dropdown value, it does not make sense to allow the user to select a city if the nation has not been chosen yet. Right? Let's see how to implement that with Formly.

Instructor: [00:00] In our Formly form here, we have these two dependent selects. Whenever I choose France and Germany, I only will get German cities.

[00:08] Notice one thing. Whenever I remove here the nation, I can still choose all of the cities. This is something I don't want to have. What I would like to have is whenever I removed the value of the nation, it doesn't make sense to be able to choose any kind of city. Therefore, I want to disable that city's control here.

[00:27] In Formly, we can disable fields by simply going to the template options and there's a disabled property and we can set that to true. As you can see, these cities are disabled. What we want to do is obviously to make them disabled depending on whether the nation has been chosen or not.

[00:46] We could definitely make use of that on any lifecycle hook here and hook into that observable stream and check whenever that nationID that comes in here basically from that observable stream is null, we then create a side effect and disable the form field by dynamically manipulating the template options.

[01:05] That's not something we want to do in this lesson here. Rather, we want to make use of another property of Formly, which are expression properties. Expression properties are dynamically evaluated expressions that allow us to set properties of our Formly field.

[01:22] In this case, we want for instance to set the template options.disabled property to be dynamic. You want to set this one here. We want to set that based on the model's value. These expression properties, if we jump into the definition, we can first of all define them as a string or as a callback function where we get a parameter of the model, the form state and actual feed configuration.

[01:50] In our case, let's simply use that callback. Let's grab here the model. Let's say whenever the model.nationID is not defined, this should actually be disabled. We can again remove here our static definition.

[02:07] Let's see whether it works. If I remove here a nation, you can see the cities gets disabled. If I again choose a nation, we again get the city enabled and filtered properly just as we expected.