Angular reactive forms guide

Angular reactive forms guide

Angular reactive forms is a new way to manage forms in angular, it helps us to manage forms in a reactive way

The classic way to manage angular forms is called template-driven form, in this way we have to write all the logic in the template ( that is not recommended ) but with reactive forms, we write the logic in component ( that is recommended )

In simple terms, reactive forms mean "Manage your forms reactively", that's why we choose it over template-driven forms

Let's give an example of reactive forms

First of all, we have to import ReactiveFormsModule form angular/forms in app.module.ts or in any other module you have declared the component that you are going to use with reactive forms, in app.module.ts

import {ReactiveFormsModule} from '@angular/forms'
import {AppComponent} from './app.component.ts'

@NgModule({
  imports: [
    //other modules
    ...,
    ReactiveFormsModule
  ],
  declarations: [AppComponent],
  bootstrap: [...]
})
export class AppModule {}

Now we have imported the necessary module, let's first add the form in app.component.html

<form [formGroup]='loginForm'>

  <div>
    <label>
      <label>Email address</label>
      <input
        type="email"
        formControlName="email"
        id="email"
        placeholder="Your email address">
    </label>
    <label>
      <label for="password">Password</span>
      <input
        type="password"
        formControlName="password"
        id="password"
        placeholder="Your password">
    </label>
  </div>
  <button type="submit">Log in</button>
</form>

Now we have our login form template, let's implement its logic in component, in app.component.ts :

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({...})
export class AppComponent implements OnInit {
  //declare loginForm variable
  loginForm: FormGroup;
  ngOnInit() {
    // init loginForm
    this.loginForm = new FormGroup({
        email: new FormControl(''),
        password: new FormControl('')
    });
  }


}

Get form values

Now we have implemented the logic, now we can get value, let give an example to get form value:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({...})
export class AppComponent implements OnInit {
  //declare loginForm variable
  loginForm: FormGroup;
  ngOnInit() {
    // init loginForm
    this.loginForm = new FormGroup({
        email: new FormControl(''),
        password: new FormControl('')
    });
  }

//get form value
getFormValue(){
// Here you will be able to see the value from form
console.log(this.loginForm.value)
// {email:'', password:''}
}


}

We just saw how to get the form value, let now call the method in the template so that we can see form value every time we submit the form, in app.component.html

<form [formGroup]='loginForm' (ngSubmit)="getFormValue)>

  <div>
    <label>
      <label>Email address</label>
      <input
        type="email"
        formControlName="email"
        id="email"
        placeholder="Your email address">
    </label>
    <label>
      <label for="password">Password</span>
      <input
        type="password"
        formControlName="password"
        id="password"
        placeholder="Your password">
    </label>
  </div>
  <button type="submit">Log in</button>
</form>

Now every time we click on the login button we should see the form value in the console

Validate form inputs

You can also validate input values, let's see how we can implement validation of our form in component, in app.component.ts

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Component({...})
export class AppComponent implements OnInit {
  //declare loginForm variable
  loginForm: FormGroup;
  ngOnInit() {
    // init loginForm
    this.loginForm = new FormGroup({
        email: new FormControl('', Validators.required),
        password: new FormControl('', [Validators.required, Validators.minLength(6)])
    });
  }

//get form value
getFormValue(){
// Here you will be able to see the value from form
console.log(this.loginForm.value)
// {email:'', password:''}
}


}

We just defined validators of our form, here's the explanation of what we have just done here:

Validators.required means that the input is required, you must fill it, at least one character

[Validators.required, Validators.minLength(6)] means that it is required also you must enter at least 6 characters to be valid

Check form status

We just saw how to validate the form, let now see how to check whether a form is valid or not, thanks to the angular team there's a built-in feature in angular/forms that helps us to check form status, let's see an example

In our example, we will make Log in button disabled if the form is not valid and make it abled when the form is valid, let's see the code:

<form [formGroup]='loginForm' (ngSubmit)="getFormValue)>

  <div>
    <label>
      <label>Email address</label>
      <input
        type="email"
        formControlName="email"
        id="email"
        placeholder="Your email address">
    </label>
    <label>
      <label for="password">Password</span>
      <input
        type="password"
        formControlName="password"
        id="password"
        placeholder="Your password">
    </label>
  </div>
  <button
 [disabled]="!loginForm.valid" 
type="submit"
>Log in</button>
</form>

As you can see, the login button will be able if the loginForm is valid otherwise it will be disabled

We have just seen some fundamentals of managing forms in angular, this is just the basis, you can add more complex logic

For deep understanding, I recommend you to visit the official documentation

I hope this article helps you to understand reactive forms, Thank you for your time

Happy coding!