Create Registration And Login Page Using Angular 7 And Web API

In this article, we will learn the step by step process of creating login and registration pages in a Web API using Angular 7.

Technologies we will use:

  • ASP.NET Web API
  • Angular 7
  • SQL Server
  • Bootstrap
Prerequisites
  • We should have basic knowledge of Angular and Web API 
  • Visual Studio Code IDE should be installed
  • SQL Server Management Studio

Step 1

Open SQL Server Management Studio, create a database named "Employee" and in this database, create a table. Give that table a name like "Employeemaster".
  1. CREATE TABLE [dbo].[Employeemaster](  
  2.     [UserId] [int] IDENTITY(1,1) NOT NULL,  
  3.     [UserName] [varchar](50) NOT NULL,  
  4.     [LoginName] [varchar](50) NULL,  
  5.     [Password] [varchar](50) NOT NULL,  
  6.     [Email] [varchar](50) NULL,  
  7.     [ContactNo] [varchar](15) NULL,  
  8.     [Address] [varchar](50) NULL,  
  9.     [IsApporved] [intNULL,  
  10.     [Status] [intNULL,  
  11.     [TotalCnt] [intNULL,  
  12. PRIMARY KEY CLUSTERED   
  13. (  
  14.     [UserId] ASC  
  15. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  16. ON [PRIMARY]  
  17.   
  18. GO  
Now, create a stored procedure with a name Usp_Login for adding the login functionality.
  1. create proc  [dbo].[Usp_Login]  
  2. @UserName varchar(50)='',  
  3. @Password varchar(50)=''  
  4. as begin  
  5.     declare @UserId int =0,@TotalCnt int =0  
  6.     select @UserId=UserId,@TotalCnt=TotalCnt from  Employeemaster um   
  7.     where LoginName=@UserName and Password=@Password and Status<>3 and IsApporved=1  
  8.     if(@TotalCnt>=5)  
  9.     begin  
  10.        select 0 UserId,'' UserName,'' LoginName,'' Password,'' Email,'' ContactNo,   
  11.     ''Address,0 IsApporved,-1 Status  
  12.     end  
  13.     if(@UserId>0)  
  14.     begin  
  15.         select UserId, UserName, LoginName, Password, Email, ContactNo,   
  16.         Address, IsApporved, Status from  Employeemaster um   
  17.         where UserId=@UserId   
  18.         --update  Employeemaster  set  Status=2 where UserId=@UserId   
  19.       
  20.     end  
  21.     else  
  22.     begin  
  23.        Update Employeemaster set @TotalCnt=TotalCnt+1    
  24.        where LoginName=@UserName and Status=1 and IsApporved=1  
  25.        select 0 UserId,'' UserName,'' LoginName,'' Password,'' Email,'' ContactNo,   
  26.     ''Address,0 IsApporved,0 Status  
  27.     end  
  28.     end  

Step 2

Open Visual Studio and create a new project.
 
Create Registration And Login Page Using Angular 7 And Web API
 
Change the name as LoginAPI and select Web API as its template.

Create Registration And Login Page Using Angular 7 And Web API 

Step 3

Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
Create Registration And Login Page Using Angular 7 And Web API 
 
Click on the "ADO.NET Entity Data Model" option and click "Add".
 
Create Registration And Login Page Using Angular 7 And Web API
 
Select EF designer from the database and click the "Next" button.

 Create Registration And Login Page Using Angular 7 And Web API
 
Add the connection properties and select database name on the next page and click OK.
 
Create Registration And Login Page Using Angular 7 And Web API 
 
Check the Tables and Stored procedure checkboxes. The internal options will be selected by default. Now, click the "Finish" button. 
 
Create Registration And Login Page Using Angular 7 And Web API 
 
Our data model is created now.

Step 4

Right-click on Models folder and add two classes - Login and Response respectively. Now, paste the following codes in these classes. 
 
Login class and Registration class
  1. public class Login  
  2. {  
  3.     public string UserName { setget; }  
  4.     public string Password { setget; }  
  5. }  
  6. public class Registration : Employeemaster { }  
Response class 
  1. public class Response  
  2. {  
  3.     public string Status { setget; }  
  4.     public string Message { setget; }  
  5. }  
Step 5
 
Right-click on the Controllers folder and add a new controller. Name it as "Login controller".
 
Add the following namespace in the Login controller. 
  1. using LoginAPI.Models;   
Now, add a method to insert data into the database for user registration. 
  1. [Route("Api/Login/createcontact")]  
  2.        [HttpPost]  
  3.        public object createcontact(Registration Lvm)  
  4.        {  
  5.            try  
  6.            {  
  7.                DemologinEntities db = new DemologinEntities();  
  8.                Employeemaster Em = new Employeemaster();  
  9.                if (Em.UserId == 0)  
  10.                {  
  11.                    Em.UserName = Lvm.UserName;  
  12.                    Em.LoginName = Lvm.LoginName;  
  13.                    Em.Password = Lvm.Password;  
  14.                    Em.Email = Lvm.Email;  
  15.                    Em.ContactNo = Lvm.ContactNo;  
  16.                    Em.Address = Lvm.Address;  
  17.                    Em.IsApporved = Lvm.IsApporved;  
  18.                    Em.Status = Lvm.Status;  
  19.                    db.Employeemasters.Add(Em);  
  20.                    db.SaveChanges();  
  21.                    return new Response  
  22.                    { Status = "Success", Message = "SuccessFully Saved." };  
  23.                }  
  24.            }  
  25.            catch (Exception)  
  26.            {  
  27.   
  28.                throw;  
  29.            }  
  30.            return new Response  
  31.            { Status = "Error", Message = "Invalid Data." };  
  32.        }   

Step 6

Add a new method for logging into the Login controller with the following lines of code.
  1. [Route("Api/Login/UserLogin")]  
  2.        [HttpPost]  
  3.        public Response Login(Login Lg)  
  4.        {  
  5.            DemologinEntities DB = new DemologinEntities();  
  6.            var Obj = DB.Usp_Login(Lg.UserName, Lg.Password).ToList<Usp_Login_Result>().FirstOrDefault();  
  7.            if (Obj.Status == 0)  
  8.                return new Response { Status = "Invalid", Message = "Invalid User." };  
  9.            if (Obj.Status == -1)  
  10.                return new Response { Status = "Inactive", Message = "User Inactive." };  
  11.            else  
  12.                return new Response { Status = "Success", Message = Lg.UserName };  
  13.        }  
Complete Login controller
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using LoginAPI.Models;  
  8.   
  9. namespace LoginAPI.Controllers  
  10. {  
  11.     public class LoginController : ApiController  
  12.     {  
  13.   
  14.         //For user login   
  15.         [Route("Api/Login/UserLogin")]  
  16.         [HttpPost]  
  17.         public Response Login(Login Lg)  
  18.         {  
  19.             DemologinEntities DB = new DemologinEntities();  
  20.             var Obj = DB.Usp_Login(Lg.UserName, Lg.Password).ToList<Usp_Login_Result>().FirstOrDefault();  
  21.             if (Obj.Status == 0)  
  22.                 return new Response { Status = "Invalid", Message = "Invalid User." };  
  23.             if (Obj.Status == -1)  
  24.                 return new Response { Status = "Inactive", Message = "User Inactive." };  
  25.             else  
  26.                 return new Response { Status = "Success", Message = Lg.UserName };  
  27.         }  
  28.   
  29.         //For new user Registration  
  30.         [Route("Api/Login/createcontact")]  
  31.         [HttpPost]  
  32.         public object createcontact(Registration Lvm)  
  33.         {  
  34.             try  
  35.             {  
  36.                 DemologinEntities db = new DemologinEntities();  
  37.                 Employeemaster Em = new Employeemaster();  
  38.                 if (Em.UserId == 0)  
  39.                 {  
  40.                     Em.UserName = Lvm.UserName;  
  41.                     Em.LoginName = Lvm.LoginName;  
  42.                     Em.Password = Lvm.Password;  
  43.                     Em.Email = Lvm.Email;  
  44.                     Em.ContactNo = Lvm.ContactNo;  
  45.                     Em.Address = Lvm.Address;  
  46.                     Em.IsApporved = Lvm.IsApporved;  
  47.                     Em.Status = Lvm.Status;  
  48.                     db.Employeemasters.Add(Em);  
  49.                     db.SaveChanges();  
  50.                     return new Response  
  51.                     { Status = "Success", Message = "SuccessFully Saved." };  
  52.                 }  
  53.             }  
  54.             catch (Exception)  
  55.             {  
  56.   
  57.                 throw;  
  58.             }  
  59.             return new Response  
  60.             { Status = "Error", Message = "Invalid Data." };  
  61.         }  
  62.     }  
  63.   
  64. }  
  65.   
  66.    

Step 7

Now, let's enable Cors. Go to Tools, open NuGet Package Manager, search for Cors, and install the "Microsoft.Asp.Net.WebApi.Cors" package.
 
Create Registration And Login Page Using Angular 7 And Web API
 
Open Webapiconfig.cs and add the following lines.
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");  
  2. config.EnableCors(cors);  

Step 8

Create an Angular 7 project with a name "login" by using the following command.

ng new login

Step 9
 
Open Visual Studio Code, open the newly created project and add bootstrap to this project. 
 
npm install bootstrap --save

Step 10 

Now, create three components for the login page, registration page, and dashboard respectively. To create the components, open terminal and use the following commands.

  • ng g c login
  • ng g c register
  • ng g c dashboard
 Create Registration And Login Page Using Angular 7 And Web API
 
Step 11
 
Create a class named "register".
 
ng g class register
 
Add the required properties in the class.
  1. export class Register {  
  2.     UserName:string;  
  3.     LoginName:string;  
  4.     Password:string;  
  5.     Email:string;  
  6.     ContactNo:string;  
  7.     Address:string  
  8. }  

Step 12

Create a service to call the Web API.
 
ng g s login 
 
Open the login service and import required packages and classes. Add the following lines of code in the login.service.ts file. 
  1. import { Injectable } from '@angular/core';  
  2. import {HttpClient} from '@angular/common/http';  
  3. import {HttpHeaders} from '@angular/common/http';  
  4. import { from, Observable } from 'rxjs';  
  5. import { Register } from "../app/register";  
  6. @Injectable({  
  7.   providedIn: 'root'  
  8. })  
  9. export class LoginService {  
  10.   Url :string;  
  11.   token : string;  
  12.   header : any;  
  13.   constructor(private http : HttpClient) {   
  14.   
  15.     this.Url = 'http://localhost:14812/api/Login/';  
  16.   
  17.     const headerSettings: {[name: string]: string | string[]; } = {};  
  18.     this.header = new HttpHeaders(headerSettings);  
  19.   }  
  20.   Login(model : any){  
  21.     debugger;  
  22.      var a =this.Url+'UserLogin';  
  23.    return this.http.post<any>(this.Url+'UserLogin',model,{ headers: this.header});  
  24.   }  
  25.    CreateUser(register:Register)  
  26.    {  
  27.     const httpOptions = { headers: new HttpHeaders({ 'Content-Type''application/json' }) };  
  28.     return this.http.post<Register[]>(this.Url + '/createcontact/', register, httpOptions)  
  29.    }  
  30. }  
Step 13
 
Now, open register.component.html and add the following HTML code to design the registration form.
  1. <div class="container" style="padding-top:40px;">  
  2.     <div class="row">  
  3.       <div class="col-md-6 mx-auto">  
  4.         <div class="card mx-4">  
  5.           <div class="card-body p-4">  
  6.             <form [formGroup]="employeeForm" (ngSubmit)="onFormSubmit(employeeForm.value)">  
  7.               <h1 style="text-align:center">Register</h1>  
  8.             
  9.               <div class="input-group mb-3">  
  10.                
  11.                 <input type="text" class="form-control" placeholder="Username"  formControlName="UserName">  
  12.               </div>  
  13.               <div class="input-group mb-3">  
  14.                 <input type="text" class="form-control" placeholder="Loginname"  formControlName="LoginName">  
  15.               </div>  
  16.               <div class="input-group mb-3">  
  17.                 <input type="password" class="form-control" placeholder="Password"  formControlName="Password">  
  18.               </div>  
  19.               <div class="input-group mb-4">  
  20.                 <input type="text" class="form-control" placeholder="Email"  formControlName="Email">  
  21.               </div>  
  22.               <div class="input-group mb-4">  
  23.                 <input type="text" class="form-control" placeholder="Contact No"  formControlName="ContactNo">  
  24.               </div>  
  25.               <div class="input-group mb-4">  
  26.                 <input type="text" class="form-control" placeholder="Address"  formControlName="Address">  
  27.               </div>  
  28.               <button type="submit" class="btn btn-block btn-success">Add User</button>  
  29.             </form>  
  30.           </div>  
  31.         </div>  
  32.       </div>  
  33.     </div>  
  34.   </div>  
Step 14
 
Open register.componet.ts file and add following lines.
  1. import { Component, OnInit } from '@angular/core';    
  2. import { LoginService } from '../login.service';    
  3. import {Register} from '../register';    
  4. import {Observable} from 'rxjs';    
  5. import { NgForm, FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';    
  6.     
  7. @Component({    
  8.   selector: 'app-register',    
  9.   templateUrl: './register.component.html',    
  10.   styleUrls: ['./register.component.css']    
  11. })    
  12. export class RegisterComponent implements OnInit {    
  13.   data = false;    
  14.   UserForm: any;    
  15.   massage:string;    
  16.   constructor(private formbulider: FormBuilder,private loginService:LoginService) { }    
  17.     
  18.   ngOnInit() {    
  19.     thisthis.UserForm = this.formbulider.group({    
  20.       UserName: ['', [Validators.required]],    
  21.       LoginName: ['', [Validators.required]],    
  22.       Password: ['', [Validators.required]],    
  23.       Email: ['', [Validators.required]],    
  24.       ContactNo: ['', [Validators.required]],    
  25.       Address: ['', [Validators.required]],    
  26.     });    
  27.   }    
  28.    onFormSubmit()    
  29.   {    
  30.     const user = this.UserForm.value;    
  31.     this.Createemployee(user);    
  32.   }    
  33.   Createemployee(register:Register)    
  34.   {    
  35.   this.loginService.CreateUser(register).subscribe(    
  36.     ()=>    
  37.     {    
  38.       this.data = true;    
  39.       this.massage = 'Data saved Successfully';    
  40.       this.UserForm.reset();    
  41.     });    
  42.   }    
  43. }    
Step 15
 
Open login.componet.html and add this HTML.
  1. <div class="container" style="padding-top:60px;">  
  2.   <div class="row">  
  3.     <div class="col-md-6 mx-auto">  
  4.       <div class="card-group">  
  5.         <div class="card p-4">  
  6.           <div class="card-body">  
  7.             <form name="form" (ngSubmit)="login()" #f="ngForm">   
  8.               <h1 style="text-align:center">Login</h1>  
  9.                
  10.               <div class="input-group mb-3">  
  11.                 <div class="input-group-prepend">  
  12.                   <span class="input-group-text"><i class="icon-user"></i></span>  
  13.                 </div>  
  14.                 <input type="text" name="UserName" [(ngModel)]="model.UserName" class="form-control sty1" placeholder="Email" required>  
  15.               </div>  
  16.               <div class="input-group mb-4">  
  17.                 <div class="input-group-prepend">  
  18.                   <span class="input-group-text"><i class="icon-lock"></i></span>  
  19.                 </div>  
  20.                 <input  type="password" name="Passward" [(ngModel)]="model.Password" class="form-control"  
  21.                placeholder="Password">  
  22.               </div>  
  23.               <div>  
  24.                   <p style="color:#E92626;font-size:20px;font-weight:normal" Class="success" align="left">  
  25.                     {{errorMessage}}  
  26.                   </p>  
  27.                 </div>  
  28.               <div class="row">  
  29.                 <div class="col-6">  
  30.                   <button type="submit" class="btn btn-primary px-4">Login</button>  
  31.                 </div>  
  32.                 <div class="col-6 text-right">  
  33.                   <button type="button" class="btn btn-link px-0">Forgot password?</button>  
  34.                 </div>  
  35.               </div>  
  36.                 
  37.             </form>  
  38.           </div>  
  39.         </div>  
  40.       </div>  
  41.     </div>  
  42.   </div>  
  43. </div>  
Open login.componet.ts and add following code.
  1. import { Component, OnInit } from '@angular/core';    
  2. import { Router } from '@angular/router';    
  3. import { LoginService } from '../login.service';    
  4.  import { FormsModule } from '@angular/forms';    
  5.     
  6. @Component({    
  7.   selector: 'app-login',    
  8.   templateUrl: './login.component.html',    
  9.   styleUrls: ['./login.component.css']    
  10. })    
  11. export class LoginComponent {    
  12.     
  13.   model : any={};    
  14.     
  15.   errorMessage:string;    
  16.   constructor(private router:Router,private LoginService:LoginService) { }    
  17.     
  18.     
  19.   ngOnInit() {    
  20.     sessionStorage.removeItem('UserName');    
  21.     sessionStorage.clear();    
  22.   }    
  23.   login(){    
  24.     debugger;    
  25.     this.LoginService.Login(this.model).subscribe(    
  26.       data => {    
  27.         debugger;    
  28.         if(data.Status=="Success")    
  29.         {       
  30.           this.router.navigate(['/Dashboard']);    
  31.           debugger;    
  32.         }    
  33.         else{    
  34.           this.errorMessage = data.Message;    
  35.         }    
  36.       },    
  37.       error => {    
  38.         this.errorMessage = error.message;    
  39.       });    
  40.   };    
  41.  }     
Step 16
 
Now, open dashboard.component.html and add the following lines.
  1. <div>  
  2.   <div class="row">  
  3.     <div class="col-sm-12 btn btn-primary">  
  4.         Welcome to DashBoard  
  5.     </div>  
  6.   </div>  
  7. </div>  
Step 17
 
Now, open app-routing.module.ts file and add the following lines to create routing.
  1. import { NgModule } from '@angular/core';    
  2. import { Routes, RouterModule } from '@angular/router';    
  3. import { DashboardComponent } from './dashboard/dashboard.component';    
  4. import { LoginComponent } from './login/login.component';    
  5. import { RegisterComponent } from './register/register.component';    
  6.     
  7.     
  8. export const routes: Routes = [    
  9.   {    
  10.     path: '',    
  11.     redirectTo: 'login',    
  12.     pathMatch: 'full',    
  13.   },    
  14.   {    
  15.     path: 'login',    
  16.     component: LoginComponent,    
  17.     data: {    
  18.       title: 'Login Page'    
  19.     }    
  20.   },    
  21.   {    
  22.     path: 'Dasboard',    
  23.     component: DashboardComponent,    
  24.     data: {    
  25.       title: 'Dashboard Page'    
  26.     }    
  27.   },    
  28.   {    
  29.     path: 'AddUser',    
  30.     component: RegisterComponent,    
  31.     data: {    
  32.       title: 'Add User Page'    
  33.     }    
  34.   },    
  35. ];    
  36.     
  37. @NgModule({    
  38.   imports: [RouterModule.forRoot(routes)],    
  39.   exports: [RouterModule]    
  40. })    
  41. export class AppRoutingModule { }    
Step 18
 
Now, let us run the project and redirect the URL to the "Add User" page.
 
 Create Registration And Login Page Using Angular 7 And Web API
 
Enter the details and click on the "Add User" button. 
 
Step 19
 
Now, run the project's default URL which takes us to the login page. Enter the username and password and click "Login".  
 
Create Registration And Login Page Using Angular 7 And Web API 
 
The following message will be displayed.
 
 Create Registration And Login Page Using Angular 7 And Web API
 
Summary
 
In this article, we discussed the process of Login and Registration page creation in an application using Angular 7 and Web API.