Become a member
to unlock all features

Level Up!

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


    Add functionality to Angular Formly controls with Formly Lifecycle Hooks


    In order to be able to further interact with Formly controls at runtime, each field configuration has a hooks property. We're not talking about "React hooks" but rather about a way to "hook into the lifecycle" of a formly field. We have methods such as onInit, onChange etc.



    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: 0:00 In order to be able to further customize the behavior of our form controls here, of our Formly form controls at runtime, Formly has a concept of so-called hooks. Let's have a look how they work. If you open up here the definitions, you can see here these are of type Formly lifecycle options.

    0:20 What they consist of is of callback functions which are very similar to the one that actual Angular components also have. Let's have a look how that works. Let's, for instance, use the onInit lifecycle hook. What we get here is as a parameter in the callback function we have the field configuration that is a Formly field config type.

    0:42 Inside here, we can actually go and inspect how our field looks like. First of all, we can go to field. We can, for instance, dynamically set the template options. I could change here the label to first name changed, just to see the effect here of a Formly onInit lifecycle hook.

    1:03 Now we can see the first name changed label here appears and no more the one that we actually originally specified here. This is a very powerful way to here, for instance, issue some server-side call and based on that server-side call further customize your input form.

    1:18 You also have access here to the actual model, as well as to the actual form. Especially access to the form and the form control gives us a lot of power. Once we use that form here and the according form controls, we are actually back in reactive forms land.

    1:36 What we can easily do here is to, for instance, grab other instance of fields, like for instance the age field, and register on its valueChanges event and from that elaborate and continue as we need in our specific use case.