Create a FormControl Dynamically with Reactive Forms in Angular

    Juri StrumpflohnerJuri Strumpflohner

    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 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


    Instructor: 00:00 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.

    00:10 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.

    00:22 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.

    00:31 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.

    00:48 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.

    01:02 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.

    01:18 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.

    01:30 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.

    01:43 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.