Angular 10/9 Authentication Form: Angular FormBuilder, FormGroup, and Validators Example with Node Backend
Tags: angular
Published: 2020-03-03 02:31:40

---
title: "Angular 10/9 Authentication Form: Angular FormBuilder, FormGroup, and Validators Example with Node Backend"
published: true
description: "In this step by step post, we’ll be learning about how to create an Angular 10 web application with an authentication form for signing up users using Angular FormBuilder,  FormGroup, and Validators APIs"
tags: angular
---

Learn Angular with techiediaries.com
<img  src="https://i.imgur.com/7gQ2IPy.jpg"  />

In this step by step post, we’ll be learning about how to create an Angular 10/9 web application with an authentication form for signing up users using Angular`FormBuilder`,  `FormGroup`, and  `Validators`APIs.


![Angular 10/9 Authentication Form](https://miro.medium.com/max/603/0*cWAMrH0lZFd7Ky9c)

## > ✋✋ Join our  [Facebook group](https://www.facebook.com/groups/angular9/)  👈 to discuss anything related to Angular 10 development.

# Prerequisites

This tutorial has a few prerequisites such as:

-   Node.js and npm installed on your development machine,
-   Angular CLI 10 installed, if not use the  `npm install -g @angular/cli@next`  command to install it.

# Step 1 — Initializing your Angular 10 Project

Let’s get started by initializing an Angular 10 project.

Head over to a new command-line interface and run:

```bash
$ ng new angular-10-auth-example
```

Angular CLI will prompt if  **Would you like to add Angular routing?**  Say  **y**  and  **Which stylesheet format would you like to use?**  Pick  **CSS**.

## > ✋✋ Download our Angular ebook for free https://upscri.be/wvwuxi

# Step 2 — Generating the Authentication and Admin Components

Go back to your command-line interface and navigate to the root folder of your project:

```bash
$ cd angular-10-auth-example
```

Next, run the  `ng generate`  command to generate the components:

```bash
$ ng generate component auth  
$ ng generate component admin
```
We created two  `AuthComponent`  and  `AdminComponent`  components.

The auth component will be used to add a reactive form for getting the user’s email and password.

The admin component will be used as an example page that will be secured against access from non-authenticated users. Users will need to log in before they can access the admin page.

Next, include these two components in the routing module. Head to the  `src/app/app-routing.module.ts`  file and update it as follows:

```ts
import { NgModule } from '@angular/core';  
import { Routes, RouterModule } from '@angular/router';import { AuthComponent } from './auth/auth.component';  
import { AdminComponent } from './admin/admin.component';const routes: Routes = [  
  { path: '', pathMatch: 'full', redirectTo: 'login'},  
  { path: 'auth', component: AuthComponent },  
  { path: 'admin', component: AdminComponent }  
];@NgModule({  
  imports: [RouterModule.forRoot(routes)],  
  exports: [RouterModule]  
})  
export class AppRoutingModule { }
```

We have created three routes:

-   For the auth component,
-   For the admin component.
-   One for redirecting the empty path to the auth path.

Let’s remove this default HTML code. Open the  `src/app/app.component.html`  file and remove everything but leave  `<router-outlet>`:

```html
<router-outlet></router-outlet>
```

# Step 3 — Creating a User Model

Let’s now create a  `User`  interface. Head back to your command-line interface and run:

$ ng generate interface user

Go to the  `src/app/user.ts`  file and update it as follows:

```ts
export  interface  User {  
    email: string;  
    password: string;  
}
```

This will ensure each user will have an email and password.

Also, check out:

[What Are the New Features of HTML6?](http://shabang.dev/question/what-are-the-new-features-of-html6/)  
[What’s the HTML6 Release Date?](http://shabang.dev/question/whats-the-html6-release-date/)  
[What Is Angular 9 ivy?](http://shabang.dev/question/what-is-angular-9-ivy/)  
[How to add Bootstrap 4 to my Angular 9 app?](http://shabang.dev/question/how-to-add-bootstrap-4-to-my-angular-9-app/)  
[How to update/Upgrade Angular 8 to Angular 9 by CLI ng update?](http://shabang.dev/question/how-to-update-upgrade-angular-8-to-angular-9-by-cli-ng-update/)  
[How to Install and Use jQuery with Angular 9?](http://shabang.dev/question/how-to-install-and-use-jquery-with-angular-9/)  
[How to Upload Image Files with Laravel 7 and Angular 9?](http://shabang.dev/question/how-to-upload-image-files-with-laravel-7-and-angular-9/)  
[What Is Angular 9 ivy?](http://shabang.dev/question/what-is-angular-9-ivy/)  
[What’s Alpine.js vs, React, Vue.js and Angular?](http://shabang.dev/question/whats-alpine-js-vs-react-vue-js-and-angular/)  
[How to Use HttpClient Module and Service to Send Ajax/Http Requests in Angular 9?](http://shabang.dev/question/how-to-use-httpclient-module-and-service-to-send-ajax-http-requests-in-angular-9/)  
[How to Create a New Angular 9 Project Using npm?](http://shabang.dev/question/how-to-create-a-new-angular-9-project-using-npm/)

# Step 4 —Creating an Angular 10 Authentication Service

Next, let’s create an Angular 10 service that exports the methods required for authenticating users. In your command-line interface, run:

```bash
$ ng generate service auth
```

Go to the  `src/app/auth.service.ts`  file and update it accordingly:

```ts
import { Injectable } from '@angular/core';  
import { User } from './user';@Injectable({  
  providedIn: 'root'  
})  
export class AuthService { 

   constructor() { } 
   public signIn(userData: User){  
    localStorage.setItem('ACCESS_TOKEN', "access_token");  
   } 

   public isLoggedIn(){  
    return localStorage.getItem('ACCESS_TOKEN') !== null; } 

   public logout(){  
    localStorage.removeItem('ACCESS_TOKEN');  
  }  
}
```

The  **signIn**  method is not fully-implemented. For a real-world implementation, check out  [Using Angular HttpClient with Node & Express.js — Example POST Requests](https://www.techiediaries.com/angular-tutorial-httpclient-post/).

# Step 5 — Creating an Angular Router Guard

After creating the components, service, and model for implementing authentication.

Let’s generate a router guard that will be used for guarding the  `admin`  component from the access of the non-authenticated users.

Go back to your command-line interface and run:

```bash
$ ng generate guard auth
```

Go to the  `src/app/auth.guard.ts`  file and update it as follows:

```ts
import { Injectable } from '@angular/core';  
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';  
import { Observable } from 'rxjs';  
import { AuthService } from './auth.service';@Injectable({  
  providedIn: 'root'  
})  
export class AuthGuard implements CanActivate {  
  constructor(private authService: AuthService){}  
  canActivate(  
    next: ActivatedRouteSnapshot,  
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean { return this.authService.isLoggedIn(); }  
}
```

We start by importing  `AuthService`  and injecting it via the authentication guard’s constructor.

Next, in the  `canActivate()`  method, we implement the logic that will grant or deny access to the user by calling the  `isLoggedIn()`  method for checking if the user is logged in before activating the route.

This is simply how this works. The  `canActivate()`  method returns true if the  `isLoggedIn()`  methods return true i.e if the user is logged in. In this case, the route which has this guard applied can be accessed by the user.

Next, you only need to apply this guard to the route you want to guard.

Go to the  `src/app/app-routing.module.ts`  file and update it accordingly:

```ts
import { NgModule } from '@angular/core';  
import { Routes, RouterModule } from '@angular/router';import { LoginComponent } from './login/login.component';  
import { AdminComponent } from './admin/admin.component';  
import { AuthGuard } from './auth.guard';  
const routes: Routes = [  
  { path: '', pathMatch: 'full', redirectTo: 'login'},  
  { path: 'login', component: LoginComponent },  
  { path: 'admin', component: AdminComponent, canActivate: [AuthGuard] }  
];@NgModule({  
  imports: [RouterModule.forRoot(routes)],  
  exports: [RouterModule]  
})  
export class AppRoutingModule { }
```

We use the  `canActivate`  array of the  `admin`  route to apply  `AuthGuard`  to the route which protects it from users that are not logged in.

# Step 6 — Creating the Authentication Form

Before using reactive forms in Angular 10 we need to import  `FormsModule`  and  `ReactiveFormsModule`  in the application module.

Open the  `src/app/app.module.ts`  file and update it accordingly:

```ts
import { BrowserModule } from '@angular/platform-browser';  
import { NgModule } from '@angular/core';  
import { FormsModule, ReactiveFormsModule} from '@angular/forms';import { AppRoutingModule } from './app-routing.module';  
import { AppComponent } from './app.component';  
import { AuthComponent } from './auth/auth.component';  
import { AdminComponent } from './admin/admin.component';@NgModule({  
  declarations: [  
    AppComponent,  
    AuthComponent,  
    AdminComponent  
  ],  
  imports: [  
    BrowserModule,  
    FormsModule,  
    ReactiveFormsModule,  
    AppRoutingModule  
  ],  
  providers: [],  
  bootstrap: [AppComponent]  
})  
export class AppModule { }
```

We can now use reactive forms in our application!

Open the  `src/app/login.component.ts`  file and import:

-   `FormBuilder`,  `FormGroup`,  `Validators`  symbols that are used to create Angular reactive forms,
-   `Router`  for routing,
-   `AuthService`  and the  `User`  model.

```ts
import { FormBuilder, FormGroup, Validators } from  '@angular/forms';  
import { Router } from  '@angular/router';  
import { User } from  '../user';  
import { AuthService } from  '../auth.service';
```

Next, inject the  `FormBuilder`,  `Router`  and  `AuthService`  via the service constructor:

```ts
export class AuthComponent implements OnInit { constructor(private authService: AuthService, private router: Router, private formBuilder: FormBuilder ) { } ngOnInit() {  
  }  
}
```

Next, add these service variables:

```ts
authForm: FormGroup;  
  isSubmitted  =  false;
```

Next, in the  `ngOnInit()`  life-cycle event, create the form:

```ts
ngOnInit() {  
    this.authForm  =  this.formBuilder.group({  
        email: ['', Validators.required],  
        password: ['', Validators.required]  
    });  
}
```

Next, add a get property to make easy to access the form controls on the HTML form:

```ts
get formControls() { return this.authForm.controls; }
```

Finally, add the  `signIn()`  method:

```ts
signIn(){  
    this.isSubmitted = true;  
    if(this.authForm.invalid){  
      return;  
    }  
    this.authService.signIn(this.authForm.value);  
    this.router.navigateByUrl('/admin');  
  }
```

Next, we need to create the HTML form. Open the  `src/app/login.component.html`  file and update it as follows:

```html
<h1 style="text-align:center">  
  Angular 10 Auth Example  
</h1>  
<div class="login">  
  <h2 class="login-header">Log in</h2>  
  <form [formGroup]="authForm" class="login-container" (ngSubmit)="signIn()"> <p [ngClass]="{ 'has-error': isSubmitted && formControls.email.errors }">  
      <input type="email" placeholder="Email" formControlName="email">  
    </p> <div *ngIf="isSubmitted && formControls.email.errors" class="help-block">  
      <div *ngIf="formControls.email.errors.required">Email is required</div>  
    </div> <p [ngClass]="{ 'has-error': isSubmitted && formControls.password.errors }">  
      <input type="password" placeholder="Password" formControlName="password">  
    </p> <div *ngIf="isSubmitted && formControls.password.errors" class="help-block">  
      <div *ngIf="formControls.password.errors.required">Password is required</div>  
    </div> <p>  
      <input type="submit" value="Log in">  
    </p>  
  </form>  
</div>
```

For styling the form we’ll be using this  [codepen example](https://codepen.io/miroot/pen/qwIgC).

Open the  `src/styles.css`  and add:

```css
@import  url(https://fonts.googleapis.com/css?family=Open+Sans:400,700);  
body {  
    background: #456;  
    font-family: 'Open Sans', sans-serif;  
}
```

Next, open the  `src/app/login.component.css`  file and these styles:

```css
/* 'Open Sans' font from Google Fonts */  
@import url(https://fonts.googleapis.com/css?family=Open+Sans:400,700);  
  
  
.login {  
  width: 400px;  
  margin: 16px auto;  
  font-size: 16px;  
}  
  
.login-header,  
.login p {  
  margin-top: 0;  
  margin-bottom: 0;  
}  
  
.login-triangle {  
  width: 0;  
  margin-right: auto;  
  margin-left: auto;  
  border: 12px solid transparent;  
  border-bottom-color: rgb(15, 66, 107);  
}  
  
.login-header {  
  background: rgb(12, 77, 129);  
  padding: 20px;  
  font-size: 1.4em;  
  font-weight: normal;  
  text-align: center;  
  text-transform: uppercase;  
  color: #fff;  
}  
  
.login-container {  
  background: #ebebeb;  
  padding: 12px;  
}  
  
.login p {  
  padding: 12px;  
}  
  
.login input {  
  box-sizing: border-box;  
  display: block;  
  width: 100%;  
  border-width: 1px;  
  border-style: solid;  
  padding: 16px;  
  outline: 0;  
  font-family: inherit;  
  font-size: 0.95em;  
}  
  
.login input[type="email"],  
.login input[type="password"] {  
  background: #fff;  
  border-color: #bbb;  
  color: #555;  
}  
  
.login input[type="email"]:focus,  
.login input[type="password"]:focus {  
  border-color: #888;  
}  
  
.login input[type="submit"] {  
  background: rgb(1, 29, 51);  
  border-color: transparent;  
  color: #fff;  
  cursor: pointer;  
}  
  
.login input[type="submit"]:hover {  
  background: #17c;  
}  
  
.login input[type="submit"]:focus {  
  border-color: #05a;  
}
```

Also, add this CSS styles for error class:

```css
.has-error input[type="email"],  
.has-error input[type="password"] {  
    border-color: rgb(216, 12, 12);  
    color: rgb(230, 14, 14);  
}
```

# Step 7 — Creating the Admin Component

Go to the  `src/app/admin.component.ts`  file and update it as follows:

```css
import { Component, OnInit } from '@angular/core';  
import { Router } from '@angular/router';  
import { AuthService } from '../auth.service';@Component({  
  selector: 'app-admin',  
  templateUrl: './admin.component.html',  
  styleUrls: ['./admin.component.css']  
})  
export class AdminComponent implements OnInit { constructor(private authService: AuthService, private router: Router) { } ngOnInit() {  
  } logout(){  
    this.authService.logout();  
    this.router.navigateByUrl('/login');  
  }}
```

Next, open the  `src/app/admin.component.html`  file and add:

```html
<div style="text-align:center">  
  <h1>  
    Welcome Admin!  
  </h1>  
  <p>  
    <button (click)="logout()">  
      Logout  
    </button>  
  </p>  
</div>
```
Finally, open the  `src/app/admin.component.css`  file and add:

```css
button{  
    background: rgb(1, 29, 51);  
    border-color: transparent;  
    color: #fff;  
    cursor: pointer;  
}
```

This is the screenshot of our admin page:


![Angular 10/9 Authentication Form](https://miro.medium.com/max/535/0*GRLGjkHWzpfrV9Kk)

You can log out from the admin page and you will be redirected to the authentication form.

# Conclusion

In this tutorial, we have implemented an authentication form with validation using Angular 10 reactive forms.