Understanding reactive form in Angular.

es404020

es404020

Posted on August 4, 2021

Understanding reactive form in Angular.

Angular has two distinct way of handling form one is the template driven way and the other is the reactive form .In this post I am going to show you how is easy it is to get started with reactive form by creating a simple Username and password signup page .

Step 1:

Import the reactive form module which is ReactiveFormsModule from

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
Enter fullscreen mode Exit fullscreen mode

This gives you access to all the classes required to create a reactive form in your module.

step 2:

Create a login component by using this command on your terminal.

ng g c @component/logging 

Enter fullscreen mode Exit fullscreen mode

step 3:

import the following

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
Enter fullscreen mode Exit fullscreen mode

Create a variable of type FormGroup

form: FormGroup;
Enter fullscreen mode Exit fullscreen mode

step 4:

Configure your formGroup to accept both the username and password and set validation rules on them. Using the the validation required it shows that the field is required .

 ngOnInit() {

    this.form = this.fb.group({
      username: ['', [Validators.required]],
      password: ['', [Validators.required]]


    });

  }
Enter fullscreen mode Exit fullscreen mode

step 5:

I love creating this two special functions they show the error validation line around the input field and also scroll to the position where the error was first found this is very useful in long forms.

scrollTo(el: any): void {
        if (el) {
          el.scrollIntoView({ behavior: "smooth", block: "center" });
        }
      }

      scrollToError(): void {
        const firstElementWithError = document.querySelector(
          ".ng-invalid[formControlName]"
        );


        this.scrollTo(firstElementWithError);
      }
Enter fullscreen mode Exit fullscreen mode

step 6:

Finally my validation functions which check if all fields where correctly inputted before making an api call.

 validate() {
        this.submitted = true;


        if (this.form.invalid) {


          this.scrollToError();
        } else {

          this.submitted = false;

  //make Api call 


        }

      }

```


###step 7:
It is time to access all the logic we have written in our login.html file.
The code below calls the formGroup in the form tag.



```
 get L(){
        return this.form.controls;
    }

```


L is a getter that gives us access to the formcontrol. This has information about the formGroup. Ranging from if a form has an error or if it passed validation .



```

  <form [formGroup]="form">
        <div class="body">
            <div class="row">

                <div class="form-group col-6">
                    <label for="form34">Menu Name</label>
                    <input formControlName="username" type="text" id="form34" class="form-control"
                        [ngClass]="{ 'is-invalid': submitted && L.username.errors }">
                    <div *ngIf="submitted &&  L.username.errors" class="invalid-feedback mb-1">
                        <div *ngIf=" L.username.errors.required">
                            Please provide a username. </div>
                    </div>



                </div>

                <div class="form-group col-6">
                    <label for="form34">Menu URL</label>
                    <input formControlName="password" type="text" id="form34" class="form-control"
                        [ngClass]="{ 'is-invalid': submitted && L.password.errors }">
                    <div *ngIf="submitted &&  L.password.errors" class="invalid-feedback mb-1">
                        <div *ngIf=" L.MenuURL.password.required">
                            Please provide a password. </div>
                    </div>



                </div>















        </div>
        <div class='footer'>
            <div class="row">
                <div class="col-6">
                    <div class="float">
                        <button class="btn btn-primary" type="button" (click)="validate()">

                            <span *ngIf="!loading">Create</span>

                            <div *ngIf="loading" class="spinner-grow text-danger" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                        </button>
                    </div>
                </div>
                <div class="col-6">

                </div>
            </div>


        </div>

    </form>




```




### Complete code:


```

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


@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit { {

  submitted: boolean;

  loading: boolean = false;
  employee: any;
  form: FormGroup; 

  constructor( public fb: FormBuilder) {

  }

  ngOnInit() {

    this.form = this.fb.group({
      Email: ['', [Validators.required]],
      Password: ['', [Validators.required]]


    });

  }

 scrollTo(el: any): void {
        if (el) {
          el.scrollIntoView({ behavior: "smooth", block: "center" });
        }
      }

      scrollToError(): void {
        const firstElementWithError = document.querySelector(
          ".ng-invalid[formControlName]"
        );


        this.scrollTo(firstElementWithError);
      }

   validate() {
        this.submitted = true;


        if (this.form.invalid) {


          this.scrollToError();
        } else {

          this.submitted = false;

  //make Api call 


        }

      }


}



```


Thanks for reading 
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
es404020
es404020

Posted on August 4, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related