Become a member
to unlock all features

Level Up!

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


    Create a FormControl Dynamically with Reactive Forms in Angular


    Angular’s reactive forms make it easy to dynamically instantiate new FormControls and bind them to our data.

    In this lesson we will take a look how to take a very simple data object, how to create a reactive Angular form and render it to our HTML template for finally binding our data onto it.



    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: As you can see, we have here a very simple form, which uses the Angular reactive style of binding a form. In our code here on the component, we create a new form group.

    We initialize it with some value, which we then expose via this form here, bind it to the HTML tag. Finally, in our input field here, we bind to the first name property which we have specified in our form group.

    Now here you can see directed output value, which basically shows us the data mining works properly. As you can see, this is hard-coded.

    Basically, if we want to have here an age property instead of the name property on our form model, we would have to also go to our template and change it there, as well. Let's take a look how we could turn this quite simple form into something more dynamic.

    First of all, we define here a field name, which will be first name, and field value, which in this case will be Uri. Then we go down here on our form group, and we change it to become more dynamic.

    Here, we can use some cool ES6 features. Basically, we can define a dynamic property here on our model, which we pass to the form group, and specify the field name which we have defined up here. In the form control, we can simply then reference the value.

    Finally, we also have to go to our template, and we have to do some input binding here rather than having it hard-coded. Again, here we reference the field name which we have defined on our component class.

    You can now see that again we have the first name here. The binding still works, and now if we would like to change that model of our form which gets defined here, we could simply change it here.

    As you can see, it properly reflects on the form here. You can imagine now that these kind of fields could be passed in from the outside via some input property of the dynamic form component here, or even as a more complex structure.