Reactive form in Angular

Tram Ho


In the previous article, we have learned about Template Driven Form (you can review here ). In today’s article, I will introduce to everyone about the remaining form in Angular that is Model Driven Form.

Model-driven forms

Model Driven Forms is also known as Reactive Forms

This method avoids using directives such as ngModel , required … instead creates Object Model in Component, then creates form from them.

Basic structure of 1 Reactive Form :

As you can see in the above diagram, we initially create the entire form control tree in code by creating new instances like FormGroup , FormControl …, then to associate these instances with elements. On the template side, we continue to use the formGroup , formControlName … directives.

Regarding the control tree, also known as AbstractControl , it provides the common behaviors and properties for subclasses, in Reactive form there are 3 subclasses: FormControl , FormGroup , and FormArray :

  • FormControl is the lowest class, it corresponds to an HTML form control such as input, select, text area …
  • FormGroup is the place to store the value and valid state of a group of AbstractControl objects – be it FormControl , FormGroup , or FormArray – this is a composite form. At the top level of a form in your component is a FormGroup .
  • FormArray is a place to store the value and valid state of an array of objects in AbstractControl like FormGroup . It is also a composite form. But it’s not the highest level ingredient.

For example

To be able to use the APIs that Angular provides for manipulating Reactive forms , we need to import ReactiveFormsModule from the @angular / forms package as follows:

First we need to initialize the form in ngOnInit:

In the above code, we have created an instance formGroup is bookForm, in bookForm will have 1 FormControl the name with the initial value is 1 empty string, which is attached to one validation is required. Next in the bookForm we also create another FormGroup, a property with 2 FormControl inside it, year and stars .

So we have created 1 AbstractControl . The next thing is we need to associate these Controls with the element on the Template

Since the instance bookForm – FormGroup is the highest class, we need to use the formGroup directive to associate the form on the template side with the bookForm.

The formControl is the smallest class so we will use the formControlName directive to link

As for the property , although it is also an instance of formGroup, but not the highest class in our control tree, we will use the formGroupName directive to bind.

Update value

To update the value for formControl, there are 2 ways that is to use patchValue or setValue . In essence patchValue is called setValue callback. While patchValue only updates the specified value objects, setValue will reset all value objects in the form, if there is a missing or redundant control, the setValue function will error. For example:

But if you use setValue with the same value object as above, you will get an error, due to the lack of other formControl, instead, to use setValue we will need to pass the exact same object with the same structure as the form:

Form Builder

In addition to using the new method to initialize an instance of formControl, Angular form also gives us another way to create a Form model more quickly and conveniently, which is the Form Builder .

By injecting FormBuilder into the class we want to create the form in, we can use APIs like group , array , and control to create the form.

Note: For the API control , you may not need to write the details, but instead just declare its initial value.


In Reactive Form, there are two types of validators: Sync Validator and Async Validator :

  • Sync Validator : Like its name suggests, this is a synchronous validator, including direct validators with the form as: required, minLength, maxLength …
  • Async Validator : Asynchronous Validator means that it will have to wait for some asynchronous task to be processed before it can be validated. For example, to check the email in the registration form already exists in the database, we must call an API on the server to check, after the results are returned, now we can validate the form. register that.

Example: Since the name field is formControl, to add the validators as required and min length 16 characters to the name field of the bookForm we would do the following:

Explain a little bit of writing above, if you look through the doc of the FormBuilder, we can see that the formControl will accept 3 parameters. The first parameter is its state, the next 2 parameters are sync validators (or an array of sync validators) and async validators.

So for FormGroup and FormArray, we will write Validators for them like? Continue to look at the FormGroup doc

We can see that FormGroup takes 2 parameters, the first is the controls inside it, the second one is an object with the keys asyncValidator, updateOn, validator. So to leave all fields in the form not empty, we can add a Validator for FormGroup as follows:

Custom Validators

To be able to create validators according to our wishes, we first need to find out how a validator is structured, to grasp this, we can go to the Validator doc to find out.

The above code is the Validator required that we use the most, we can see that 1 Validator accepts a parameter called AbstractControl and returns a value of type ValidationErrors or null.

So now we try to create a Validator with the content that the user can only enter numbers, not allowed to enter other characters for the field year in the bookForm :

After creating it, we just need to use it as normal Validators:

Ok, so we have successfully custom made a validator for ourselves already


In today’s article, I have introduced to everyone about Model-Driven Form , also known as Reactive Form . It can be seen that Reactive Form is quite flexible in usage, because the form is created in the component, so manipulating the form uses js and this makes me feel much more comfortable than having to manipulate in html template. And the strength of Reactive Form is that besides the available Validators, we can create extremely powerful and effective Validators, this is probably the feature that many people prefer to use Reactive forms over Template. -driven form .

Share the news now

Source : Viblo