Menu

Forms in Angular (Part-1)

February 17, 2021 - Frontend Development
Forms in Angular (Part-1)

Forms are one of the most crucial part of any web application. A form can be as simple as taking only one text input from the user and process the user information provided. But in real world applications, this is often not the case. A lot of times forms get pretty complex.

Thankfully Angular provides us with tools to make our lives easy for creating, validating and handling behaviors of the form.

FormControls — All the inputs of a form are encapsulated in an object so that we can get and work with the values from just a single object.

Validators — Handes the validations of the provided user data.

Observers — Observing the changes in a form and triggering responses according to the changes.

FormControl

This is one of the most fundamental objects in Angular forms. We bind this object with each input fields of the form where we want to take inputs from the users. FormControl gets the form values and also the different states of the fields such as Errors, Dirty, Valid.

The way we use FormControl in our templates –

<input type="text" [formControl]="name" />

As I have already mentioned that FormControl are gives us an object we can handle these objects individually in our component. We might want to do something like the below code in our Controller.

let name = new FormControl("John");

name.errors  // Triggers when error occurs
name.dirty //Triggers when forms get dirty
name.valid // Triggers when form is valid

Usually our forms does not contain with only one field. So there will be a number of fields where we would want to use FormControl in. Handling FormControl individually for each field might become cumbersome at times. Angular provides us with a FormGroup Object which makes this process easy. We can group multiple FormControl in a single group with the help of FormGroup. See the below code to have a look at the convenience we get from using FormGroup —

let userInfo = new FormGroup({
firstName: new FormControl("John"),
lastName: new FormControl("Doe"),
age: new FormControl(30)
})


useInfo.value; 
/**
* Output of userInfo.value
* {
* firstName: "Nate",
* lastName: "Murray",
* age: 30
* }
*
*/

Here you can see that the value of the FormGroup was returned as an Object with key-value pair. This is a really handy way to get all the values form values.

userInfo.errors
userInfo.dirty
userInfo.valid

As you can see that grouped our FormControl with FormGroup and performed different operations on it rather than doing them individually.

In our next Part we are going to create an Angular form right from the scratch. Stay Tuned.

Leave a Reply

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