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:

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] [int] NULL,
  10. [Status] [int] NULL,
  11. [TotalCnt] [int] NULL,
  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 = ON) ON [PRIMARY]
  16. ) ON [PRIMARY]
  17. 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. end
  20. else
  21. begin
  22. Update Employeemaster set @TotalCnt=TotalCnt+1
  23. where LoginName=@UserName and Status=1 and IsApporved=1
  24. select 0 UserId,'' UserName,'' LoginName,'' Password,'' Email,'' ContactNo,
  25. ''Address,0 IsApporved,0 Status
  26. end
  27. 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 { set; get; }
  4. public string Password { set; get; }
  5. }
  6. public class Registration : Employeemaster { }
Response class
  1. public class Response
  2. {
  3. public string Status { set; get; }
  4. public string Message { set; get; }
  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. throw;
  28. }
  29. return new Response
  30. { Status = "Error", Message = "Invalid Data." };
  31. }

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. namespace LoginAPI.Controllers
  9. {
  10. public class LoginController : ApiController
  11. {
  12. //For user login
  13. [Route("Api/Login/UserLogin")]
  14. [HttpPost]
  15. public Response Login(Login Lg)
  16. {
  17. DemologinEntities DB = new DemologinEntities();
  18. var Obj = DB.Usp_Login(Lg.UserName, Lg.Password).ToList<Usp_Login_Result>().FirstOrDefault();
  19. if (Obj.Status == 0)
  20. return new Response { Status = "Invalid", Message = "Invalid User." };
  21. if (Obj.Status == -1)
  22. return new Response { Status = "Inactive", Message = "User Inactive." };
  23. else
  24. return new Response { Status = "Success", Message = Lg.UserName };
  25. }
  26. //For new user Registration
  27. [Route("Api/Login/createcontact")]
  28. [HttpPost]
  29. public object createcontact(Registration Lvm)
  30. {
  31. try
  32. {
  33. DemologinEntities db = new DemologinEntities();
  34. Employeemaster Em = new Employeemaster();
  35. if (Em.UserId == 0)
  36. {
  37. Em.UserName = Lvm.UserName;
  38. Em.LoginName = Lvm.LoginName;
  39. Em.Password = Lvm.Password;
  40. Em.Email = Lvm.Email;
  41. Em.ContactNo = Lvm.ContactNo;
  42. Em.Address = Lvm.Address;
  43. Em.IsApporved = Lvm.IsApporved;
  44. Em.Status = Lvm.Status;
  45. db.Employeemasters.Add(Em);
  46. db.SaveChanges();
  47. return new Response
  48. { Status = "Success", Message = "SuccessFully Saved." };
  49. }
  50. }
  51. catch (Exception)
  52. {
  53. throw;
  54. }
  55. return new Response
  56. { Status = "Error", Message = "Invalid Data." };
  57. }
  58. }
  59. }

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. this.Url = 'http://localhost:14812/api/Login/';
  15. const headerSettings: {[name: string]: string | string[]; } = {};
  16. this.header = new HttpHeaders(headerSettings);
  17. }
  18. Login(model : any){
  19. debugger;
  20. var a =this.Url+'UserLogin';
  21. return this.http.post<any>(this.Url+'UserLogin',model,{ headers: this.header});
  22. }
  23. CreateUser(register:Register)
  24. {
  25. const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
  26. return this.http.post<Register[]>(this.Url + '/createcontact/', register, httpOptions)
  27. }
  28. }
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. <div class="input-group mb-3">
  9. <input type="text" class="form-control" placeholder="Username" formControlName="UserName">
  10. </div>
  11. <div class="input-group mb-3">
  12. <input type="text" class="form-control" placeholder="Loginname" formControlName="LoginName">
  13. </div>
  14. <div class="input-group mb-3">
  15. <input type="password" class="form-control" placeholder="Password" formControlName="Password">
  16. </div>
  17. <div class="input-group mb-4">
  18. <input type="text" class="form-control" placeholder="Email" formControlName="Email">
  19. </div>
  20. <div class="input-group mb-4">
  21. <input type="text" class="form-control" placeholder="Contact No" formControlName="ContactNo">
  22. </div>
  23. <div class="input-group mb-4">
  24. <input type="text" class="form-control" placeholder="Address" formControlName="Address">
  25. </div>
  26. <button type="submit" class="btn btn-block btn-success">Add User</button>
  27. </form>
  28. </div>
  29. </div>
  30. </div>
  31. </div>
  32. </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. @Component({
  7. selector: 'app-register',
  8. templateUrl: './register.component.html',
  9. styleUrls: ['./register.component.css']
  10. })
  11. export class RegisterComponent implements OnInit {
  12. data = false;
  13. UserForm: any;
  14. massage:string;
  15. constructor(private formbulider: FormBuilder,private loginService:LoginService) { }
  16. ngOnInit() {
  17. thisthis.UserForm = this.formbulider.group({
  18. UserName: ['', [Validators.required]],
  19. LoginName: ['', [Validators.required]],
  20. Password: ['', [Validators.required]],
  21. Email: ['', [Validators.required]],
  22. ContactNo: ['', [Validators.required]],
  23. Address: ['', [Validators.required]],
  24. });
  25. }
  26. onFormSubmit()
  27. {
  28. const user = this.UserForm.value;
  29. this.Createemployee(user);
  30. }
  31. Createemployee(register:Register)
  32. {
  33. this.loginService.CreateUser(register).subscribe(
  34. ()=>
  35. {
  36. this.data = true;
  37. this.massage = 'Data saved Successfully';
  38. this.UserForm.reset();
  39. });
  40. }
  41. }
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. <div class="input-group mb-3">
  10. <div class="input-group-prepend">
  11. <span class="input-group-text"><i class="icon-user"></i></span>
  12. </div>
  13. <input type="text" name="UserName" [(ngModel)]="model.UserName" class="form-control sty1" placeholder="Email" required>
  14. </div>
  15. <div class="input-group mb-4">
  16. <div class="input-group-prepend">
  17. <span class="input-group-text"><i class="icon-lock"></i></span>
  18. </div>
  19. <input type="password" name="Passward" [(ngModel)]="model.Password" class="form-control"
  20. placeholder="Password">
  21. </div>
  22. <div>
  23. <p style="color:#E92626;font-size:20px;font-weight:normal" Class="success" align="left">
  24. {{errorMessage}}
  25. </p>
  26. </div>
  27. <div class="row">
  28. <div class="col-6">
  29. <button type="submit" class="btn btn-primary px-4">Login</button>
  30. </div>
  31. <div class="col-6 text-right">
  32. <button type="button" class="btn btn-link px-0">Forgot password?</button>
  33. </div>
  34. </div>
  35. </form>
  36. </div>
  37. </div>
  38. </div>
  39. </div>
  40. </div>
  41. </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. @Component({
  6. selector: 'app-login',
  7. templateUrl: './login.component.html',
  8. styleUrls: ['./login.component.css']
  9. })
  10. export class LoginComponent {
  11. model : any={};
  12. errorMessage:string;
  13. constructor(private router:Router,private LoginService:LoginService) { }
  14. ngOnInit() {
  15. sessionStorage.removeItem('UserName');
  16. sessionStorage.clear();
  17. }
  18. login(){
  19. debugger;
  20. this.LoginService.Login(this.model).subscribe(
  21. data => {
  22. debugger;
  23. if(data.Status=="Success")
  24. {
  25. this.router.navigate(['/Dashboard']);
  26. debugger;
  27. }
  28. else{
  29. this.errorMessage = data.Message;
  30. }
  31. },
  32. error => {
  33. this.errorMessage = error.message;
  34. });
  35. };
  36. }
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. export const routes: Routes = [
  7. {
  8. path: '',
  9. redirectTo: 'login',
  10. pathMatch: 'full',
  11. },
  12. {
  13. path: 'login',
  14. component: LoginComponent,
  15. data: {
  16. title: 'Login Page'
  17. }
  18. },
  19. {
  20. path: 'Dasboard',
  21. component: DashboardComponent,
  22. data: {
  23. title: 'Dashboard Page'
  24. }
  25. },
  26. {
  27. path: 'AddUser',
  28. component: RegisterComponent,
  29. data: {
  30. title: 'Add User Page'
  31. }
  32. },
  33. ];
  34. @NgModule({
  35. imports: [RouterModule.forRoot(routes)],
  36. exports: [RouterModule]
  37. })
  38. 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.