Become a member
to unlock all features

Level Up!

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


    Dynamically Create Multiple FormControls from a Data Set in Angular


    In this lesson we will take a look how to create a more complex but also more real-world example. We’re creating a simple person object and by iterating over its properties we dynamically create multiple FormControl instances using Angular’s reactive forms approach.



    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: Our simple dynamic form here works, as you can see here from the binding, but it is quite limited because normally, you don't have just two fields, but you have a couple fields. Let's see how we could render even a more complex object.

    Let's create here a person, and directly initialize it with a first name property and some age. We can now do the same thing which we did before, but now by iterating over those person objects' properties.

    Let's take here out our form object and initialize it to an empty one, and now we basically iterate over our person object above. We can do that by using the object.keys, and now we simply say the form data object, and we set a new property, which will be the property of our person here, and we initialize it to the according value.

    As you can see, we create here a form control. We associate it to our form data model, and then we store everything inside here. Next, we need here below to remove that inline form definition, and basically assign our form data object.

    You can now see that our form value array reflects our updated form, so you can see the first name and age property. Now we also need to render basically input fields for each of our properties which we have.

    First of all, let's store the person property names here, and here while we iterate over these properties, we also update here our array and push in the property name. This is quite handy, because now we can use this structure here to iterate over in our template.

    We create here a div, such that each input field gets its new line, and we use a simple NG4, and we iterate over those person properties. You can imagine that the next step here is to simply change this from the field name to the property, which will be the person property, and if we save here, you can see how the values get reflected.

    Also, if we now have a person object, then we want also surname property, and maybe even a Twitter handle. We can simply save here, and you see that without any change in our template, it gets reflected on the UI, and it also data mines properly.