Basic steps to create Reactive forms and Form Validation:
Know about Angular Forms:
Angular forms are used to deal with user inputs. It can include a massive no of input fields, spanning more than one tab. Forms may include complicated validation logic interdependent on multiple fields.
Some things forms are anticipated to do
- Initialize the forms fields and gift them to the user
- Collect the user information
- Track adjustments made to the fields
- Validate the inputs
- Display useful errors(mistakes) to the user
Angular forms module offers all the above services. It binds the form field values to the Angular component class. It tracks adjustments made to the form fields in order that we can respond accordingly. The Angular forms will provide the built-in validators to validate the inputs.
Multiple approaches in angular forms creation:
There are 2 approaches to dealing with user input through forms:
- Reactive forms
- Template-driven forms
Reactive Forms approach
In Reactive Forms or Model-driven approaches, the logic of the form is described in the component as an object. The Model-driven approach has extra blessings as it makes the testing of the component easier.
Template-driven forms approach
In Template-driven approach is the simplest way to build the Angular forms. Template contains the logic of the form.
Steps to create Reactive Forms and custom validator:
Angular reactive forms follow a model-driven approach to handle form input whose values may be modified over time. These are also referred to as model-driven forms. In component class we can define the structure of the form. We can create the form model with Form Groups, Form Controls, and Form Arrays. We can create and update multiple form controls and define the validation rules in the component class. Create the HTML Form resembling the Form Model and bind the HTML Form to the Form Model.
1. Register the reactive forms module
You have to import ReactiveFormsModule from the @angular/forms package and add it to NgModule’s imports array to use reactive forms.
2. Generate and Import a new form control
First step: Generate a component for the control by running the following command:
ng generate component create-edit-person-form
The FormControl class is the fundamental constructing block used in reactive forms. To create and use a form control, you have to import the FormControl class into your component. Create a new instance of this form control to save it as a class property.
Write the following code in create-edit-person-form.component.ts file:
3. Now, register the control in the HTML form
After creating the control in the component class, you have to add it to the form control element in the HTML form template. Following is a regular HTML form which is enclosed with