Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Dynamically disable a Form field with Angular Formly


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




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

    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.

    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.

    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.

    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.

    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.

    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.

    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.