In the last section, we have understood how to use template driven forms in Angular. In this section, we will focus on how to make use of reactive forms. This approach allows user to create form in greater detail. Here, we will create the forms programmatically in TypeScript.
Let me paste the snippet here first. Here, I have used FormGroup, FormGroup is basically Forms package, which contains lots of classes which we will work with in coming sections. Therefore, overall Form is just a form group.
And, also in app.module.ts, this should be reactive forms module rather than forms module.
So, these are the only changes, which we need to do for reactive setup. Now, let’s focus on forms now. Below, I have pasted finished snippet for the same.
Now, this code needs to be connected with template code. For that, in the Form tag, I need to tell this explicitly, else it will give error. Therefore, I need to tell like Here, I am explicitly telling that consider the form group which I have created. This is also known how you link your typescript code with markup code. But, still we need to tell which control is associated with which inputs in the markup. For that, we use another directive say formControlName like shown below. Below is the finished content for the form.
With that being said, when I run the app, it will appear like
Here, its pre-populated with default values as I passed in. This way we have successfully, synchronized our HTML Form with our TypeScript Form. Let’s handle submit action now. Below is the finished snippet for the same.
Now, the difference is we don’t need to access the form via local reference rather we can simply refer our TypeScript form which is already connected.
Now, let’s add validation here in the form. Usually for validation, we used to configure in HTML code in template driven forms. But, it doesn’t work like this in reactive forms. Here, we already have overloaded constructor, which we can use for validation purpose. Below is the finished snippet for the same.
As you can see, here I have done couple of things like first imported validators from angular forms module then used the same in constructor itself. In case of multiple validations, we can pass the same in array itself. With that being said, you can see the same validation like shown below. Now, let’s see how to display the messages. Below is the finished snippet for the same.
Here, in order to get the access of controls, we can get the same by using get validator. With that change in place, it will display the following error message.
With this I would like to wrap this up. In the next section, we will delve further. Till then stay tuned and Happy Coding.
1,350 total views, 1 views today