Javatpoint Logo
Javatpoint Logo

Angular Reactive Forms

Angular reactive forms follow a model-driven approach to handle form input whose values can be changed over time. These are also known as model-driven forms. In reactive forms, you can create and update a simple form control, use multiple controls in a group, validate form values, and implement more advanced forms.

Reactive forms use an explicit and immutable approach to manage the state of the form at a given point of time. When we change the form state, it returns a new state which manages the integrity of the models between changes. In reactive forms, you build your own representation of a form in the component class.

Reactive forms are easy to test because they assure consistent and predictable data when requested.

How to add a single form control

In this section, we will describe how to add a single form control. Here, the users have to enter their name into an input field, form captures that input value, and displays the current value of the form control element.

Follow these steps:

1. Register the reactive forms module

You have to import ReactiveFormsModule from the @angular/forms package and add it to your NgModule's imports array to use reactive forms.

2. Generate and Import a new form control

First, generate a component for the control by using the following syntax:

To register a single form control, you have to import the FormControl class into your component and create a new instance of the form control to save as a class property. The FormControl class is the basic building block used in reactive forms.

Write the following code in name-editor.component.ts file:

3. Now, register the control in the template

After creating the control in the component class, you have to add it to the form control element in the template. Use the formControl binding provided by FormControlDirective to update the template with the form control.

We have registered the form control to the name input element in the template. Now, the form control and DOM element communicate with each other and the view reflects changes in the model, and the model reflects changes in the view.

4. Display the component

Add the form control component to the template to display the form. Add the following code to app.component.html.

Output:

Angular Reactive Forms




Help Others, Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA