What is reactive form in angular 4?

reactive form




There are two ways to create forms in angular 4. First is Template Driven and second reactive form.
In this post, I am going to discuss Reactive Form.

Template Driven

This is the easiest way to create a form in angular to bind data. In this method, you need to usengForm and ngModel direcitve to bind data.

Example

Reactive Form

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. This guide shows you how to create and update a simple form control, progress to using multiple controls in a group, validate form values and implement more advanced forms.

The reactive form is different from Template – Driven. In reactive form method, you need to use ReactiveFormsModule module.
There are some important terms that you need to know before the start.

FormBuilder

It is very important to initialize reactive form in angular 4.It provides the features to create instance of FormArray, FormGroup, Validators

FormGroup

FormGroup combine the value of each child element of FormControl in a single object. It also manage the value and validity state.

FormControl

FormControl track the value of single element.

Validators

Validators are very useful feature of reactive forms. By using this we can implement custom validation in .ts file.

Simple example of reactive form

To create reactive form, you need to import

and need to inject import ReactiveFormsModule in app.module.ts

I am going to create a Login form.

Step 1:

Create a component “login.component.ts”.

Step 2:

login.component.html

In the above code, I have used formGroup,FormBuilder, Validators and FromControl. You can define FormControl either in HTML or ts file. It depends on your ease.

Update form value from component class

There are two methods available to update the form values setValue and patchValue.

setValue :

If you want o set all form value then you need to use this because in this method you can not exclude any value otherwise it will give an error.

patchValue :

If you want o set selected form value then you need to use this because in this method works fine to set some values in the form.

Conclusion

ReactiveForm has more control over forms. You can customize Validation in your component, no need to write validation on the HTML page. It has also provided methods like setValue and patchVlaue to control form values.

Please follow and like us:

You May Also Like

About the Author: Sujeet Kumar

Sujeet is Web and Android Devloper with a soft spot for functional programming. I like to play cricket, regular workout.

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *