Starting with Reactive forms in Angular

Jai Sai Chand
3 min readMar 6, 2022

Hey Guys, Hope you all are doing well. If you are like me, who wants to refer to an online article every time before starting to do reactive forms this might very well help you.

To get started there are two types of forms in angular.

  1. Template-driven forms
  2. Reactive or model-driven forms

Most people use reactive forms as they are more powerful and easy to use.

Here I am giving a detailed step-by-step process on how to create a basic form using reactive forms in angular.

Step 1: Import ReactiveFormsModule into whichever module you want to use the form in. In this case, it is the app module. This allows us to do reactive forms.

Step 2: As this is the form that is model-driven, we first start from the component’s logic. Head to the ts file and create a formGroup which in turn contains formControls(inputs) like shown in the below image. In this, we can have the default input value as the first parameter for the formControl.

Step 3: Now we have to create an actual form in the HTML file with the form tag. We can bind the formGroup that we created in the ts file to the form tag in the HTML like shown in the below image (<form [formGroup]=”registerForm” (ngSubmit)=”onSubmit(registerForm)” >). here we are also listening to the submit click of the form and listening to the event ngSubmit.

Step 4: We should add formContolName to the inputs inside the form tag. the names that we have in the formControlName should be the formControls that we have given in the formGroup (refer to the below image)

Step 5: We can also add validators to the inputs through form group. We can add the validators to a formControl as the second parameter for the formControl. We can add multiple validators to a single formControl(input). (refer to below image)

Step 6: We can check if the input value has satisfied the validations and we can even display an error message.(refer to the below image)

Hope I have made reactive forms at least a little bit easy for you.

Code for the above is at https://github.com/jaisaichand/angular-reactive-blog

Feel free to mail to t.jaisaichand4@gmail.com if anything in the article needs to be improved or corrected.

--

--

Jai Sai Chand

Versatile Full-stack Developer with experience in development, and managing complex applications and internal frameworks.