Reactive Forms In Angular
Published: 2022-07-28 14:23:36

Hi readers 👋, glad to have you as a part of my learning journey! 
Last week was a bit rough, back again this week with the fifth blog. 

For the new readers, I document my learning journey in the series "Getting Started With Angular", hoping it can help people learn.

This week we will be learning about Reactive Forms. 

## What Are Reactive Forms?

Reactive forms provide a model-driven approach to handling form inputs whose values change over time. Validation logic and
initial state of controls are defined by model object. Each change in the form state returns a new state of the model. Every control of reactive forms emits an observable, which gives status and value of the form controls. Reactive forms also provide a straightforward path to testing because you are assured that your data is consistent and predictable when requested.

## Adding a Basic Form Control

There are three steps to using form controls:

- Register the reactive forms module in your application. This module declares the reactive-form directives that you need to use reactive forms.

- Generate a new `FormControl` instance and save it in the component.

- Register the `FormControl` in the template.

### Importing ReactiveFormsModule

```typescript
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // other imports ...
    ReactiveFormsModule
  ],
})
export class AppModule { }
```


### Creating a FormControl

After the module is imported, we import the class `FormGroup`. The `FormControl` class corresponds to one individual form control,
tracking its value and validity.

```ts
export class AppComponent {
email = new FormControl(‘’);
}
```

Using email `FormControl`:

```ts
<input [formControl]=’email’
type=”text”

Reactive Forms 79

placeholder=”Enter Email” />
{{email.value | json}}
```

### Creating FormGroup
`FormGroup` is a group of `FormControls`. In a form, there is expected to be more than one control, this is when `FormGroup` comes to  play. 

Example: Creating a form with two controls - email and password

```ts
loginForm = new FormGroup({
email: new FormControl(‘ ‘),
password: new FormControl(‘ ‘)
});
```
Using both the controls, here's how the entire code will look like:

```ts
<form [formGroup]=’loginForm’ novalidate class=”form”>
<input formControlName=’email’
type=”text”
class=”form-control”
placeholder=”Enter email” />
<input formControlName=’password’
type=”password”
class=”form-control”
placeholder=”Enter password” />
</form>
{{loginForm.value | json}}
{{loginForm.status | json }}
```

### Using FormBuilder

Creating form control instances manually can become repetitive when dealing with multiple forms. The `FormBuilder` service provides convenient methods for generating controls.

The first step is to import `Form Builder` and injecting it:

``` ts
import { FormBuilder } from '@angular/forms';
constructor(private fb: FormBuilder) { }

```
Using the same login form example, this is how the code will look:

```ts

import { Component, OnInit } from ‘@angular/core’;
import { FormGroup, FormControl, FormArray, Validators,
FormBuilder } from ‘@angular/forms’;
@Component({
selector: ‘app-root’,
templateUrl: ‘./app.component.html’,
styleUrls: [‘./app.component.css’]
})
export class AppComponent implements OnInit {
loginForm: FormGroup;
constructor(private fb: FormBuilder) {
}
ngOnInit() {
this.loginForm = this.fb.group({
email: [null, [Validators.required,
Validators.minLength(4)]],
password: [null, [Validators.required,
Validators.maxLength(8)]]
});
}
loginUser() {
console.log(this.loginForm.status);
console.log(this.loginForm.value);
}
}
```
## Ending Notes
Thank you for reading till the end. 

Most of my learning credit goes to:
- [Angular docs](https://angular.io/docs)
- Books by [Dhananjay Kumar](https://twitter.com/debug_mode) and [Christoffer Noring](https://twitter.com/chris_noring)


With these blogs, I expect to note my journey and help more people.

For any questions or suggestions, drop them on the comments below or reach out to me [@Haimantika](https://twitter.com/HaimantikaM).