Tutorial creates a login form on angular 4 for beginners. A large application both desktop and web applications, of course, requires a login page as the access door to the main application. Implementing login form PHP and login form angular 4 is very different. In this article, I will share a simple tutorial how to create an angular 4 login form using REST API for beginner level for easy to understand.
This article is a continuation of previous posts Angular 4 Tutorial For Beginner With Simple App Project. To be able to understand this tutorial well, you should first read the article. To find out how the application work, please refer to the following video
In this article do not discuss angularjs user registration, but rather just create a simple login page.
Table of Contents
Getting Started
As an initial preparation for the application login form angular 4 can run well, you need a “m_user” table on the “pos” database, or please see the following picture
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | DROP TABLE IF EXISTS 'm_item'; CREATE TABLE 'm_item' ( 'id_item' varchar(6) NOT NULL, 'item_name' varchar(100) DEFAULT NULL, 'note' text, 'stock' decimal(10,2) DEFAULT '0.00', 'price' int(14) DEFAULT '0', 'unit' varchar(4) DEFAULT 'PCS', PRIMARY KEY ('id_item'), UNIQUE KEY 'unik' ('item_name') ) ENGINE=MyISAM DEFAULT CHARSET=latin1; /*Data for the table 'm_item' */ insert into 'm_item'('id_item','item_name','note','stock','price','unit') values ('PB0001','Razor Blade','best razor blade in the world',8.00,12000,'PCS'); insert into 'm_item'('id_item','item_name','note','stock','price','unit') values ('PB0002','Muscle Face','for build body',10.00,50000,'PCS'); insert into 'm_item'('id_item','item_name','note','stock','price','unit') values ('PB0007','GALAXY NOTE 1','test 1 2 3 4 5 6',5.00,5000,'PCS'); /*Table structure for table 'm_user' */ DROP TABLE IF EXISTS 'm_user'; CREATE TABLE 'm_user' ( 'id_user' int(11) NOT NULL AUTO_INCREMENT, 'username' varchar(20) NOT NULL, 'pass_user' char(50) NOT NULL, 'h_menu' varchar(254) DEFAULT NULL, 'uniq_login' varchar(15) DEFAULT NULL, PRIMARY KEY ('id_user'), UNIQUE KEY 'NewIndex1' ('username') ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=latin1; /*Data for the table 'm_user' */ insert into 'm_user'('id_user','username','pass_user','h_menu','uniq_login') values (6,'ADMIN','202cb962ac59075b964b07152d234b70','1,2,3','58f72048cc33114'); |
Web API / Restful API Server to access data you can download here.
Make sure you change the database settings in a dbconn.php file and customize it with your database configuration.
If the above preparations have been completed, the next step We will make the main application.
Login Form App Angular 4 For Beginner
Create new angular 4 project or review the project from the previous article:
1 | ng new learnangular4 |
We need a two component and two services.
Data service
Create a service with the name data.service.ts with the following command
1 | ng g service service/data |
This service is used to store login and logout functions to be executed by login page and logout button
Edit data.service.ts and copy the following script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import { Injectable } from '@angular/core'; import { Http, Response, RequestOptions, Headers } from '@angular/http'; import { Observable } from 'rxjs/Rx'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; @Injectable() export class DataService { private url: string = 'http://localhost/restapiserver/api/'; constructor(private http: Http) { } login(post): Observable<any> { console.log(post); const getLoginUrl = this.url + 'get/login/' + post['username'] + '/' + post['password']; return this.http .get(getLoginUrl, {}) .map( res => { if (res.json().status == true) { localStorage.setItem('currentUser', JSON.stringify(res.json().data)); } return res.json(); }, err => { return err; } ) } logout() { localStorage.removeItem('currentUser'); } getItem(): Observable<any> { const getItemUrl = this.url + 'get/item/list'; return this.http .get(getItemUrl, {}) .map( res => { return res.json(); }, err => { return err; } ) } } |
A brief description:
- Don’t forget to change web api url1private url: string = 'http://localhost/restapiserver/api/';
Change “localhost” with your ip or domain name - If the return value of res.status is true, user data will be stored into local storage with the currentUser name
Implementation of local storage more detail you can read here
Authguard Service
This service used to create the Interface to protect the route whether it can be active. Also, we will implement canActivate guard to protect the route from unauthorized users..
Create a service with the name authguard.service.ts with the following command
1 | ng g service service/authguard |
Edit authguard.service.ts and copy the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import { Injectable } from '@angular/core'; import {Router,CanActivate,ActivatedRouteSnapshot,RouterStateSnapshot} from '@angular/router'; @Injectable() export class AuthguardService implements CanActivate { constructor(private router:Router) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { if (localStorage.getItem('currentUser')) { return true; } // not logged in so redirect to login page with the return url this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }}); return false; } } |
A brief description:
If the local storage is empty, it will redirect to the login page.
Login Component.
Create a new component with the following command
1 | ng g component login |
Edit login.component.ts and add the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | import { Component, OnInit,ElementRef,ViewChild } from '@angular/core'; import { Router, NavigationExtras,ActivatedRoute } from '@angular/router'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { DataService } from '../service/data.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'], providers: [DataService] }) export class LoginComponent implements OnInit { @ViewChild('username') el:ElementRef; statuslogin:any; focusin: boolean = true; rForm: FormGroup; post:any; usernameAlert:string="Please fill username"; passwordAlert:string="Please fill password"; loginAlert:string; loginError:boolean=false; returnUrl: string; constructor( private route: ActivatedRoute, private fb: FormBuilder, private authenticationservice:DataService, public router: Router ) { this.rForm = fb.group({ 'username' : [null, Validators.required], 'password' : [null, Validators.required], }); } ngOnInit() { this.authenticationservice.logout(); this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/index'; } addPost(post) { this.authenticationservice.login(post).subscribe( res => { if(res.status == true) { this.router.navigate([this.returnUrl]); }else{ this.loginError = true this.loginAlert = res.message; } }, err => { return err; } ); } } |
Edit login.component.html and add the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <form [formGroup]="rForm" (ngSubmit)="addPost(rForm.value)"> <div class="form-container"> <div class="row columns"> <h1>Login</h1> <label>Username <input type="text" #usernameobj appAutofocus formControlName="username"> <div class="alert" *ngIf="!rForm.controls['username'].valid && rForm.controls['username'].touched">{{ usernameAlert }}</div> </label> <label>Password <input type="password" formControlName="password"> <div class="alert" *ngIf="!rForm.controls['password'].valid && rForm.controls['password'].touched">{{ passwordAlert }}</div> </label> <div class="callout warning" *ngIf="loginError"> {{ loginAlert }}</div> <input type="submit" class="button expanded" value="Login" [disabled]="!rForm.valid"> </div> </div> </form> |
A brief description:
I did not include the angular 4 autofocus input box directive script in this article, but you can directly download it from project source files
Home Component
Home component used as dashboard page after login successful.
Create home component with this command in terminal
1 | ng g component home |
Edit home.component.ts and add the following script
1 2 3 4 5 6 7 8 | <nav> <ul class="menu"> <li class="is-active"><a routerLink="/login" routerLinkActive="active">Logout</a></li> <li><a routerLink="/index/listitem" routerLinkActive="active">List Item</a></li> </ul> </nav> <hr> <router-outlet></router-outlet> |
Add an angular routing with app.routing.ts name and copy the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | import { Routes, RouterModule } from '@angular/router'; import { ListitemComponent } from './item/listitem/listitem.component'; import { LoginComponent } from './login/login.component'; import { HomeComponent } from './home/home.component'; import { AuthguardService } from './service/authguard.service'; const appRoutes: Routes = [ { path: 'login', component: LoginComponent }, { path: 'index', component: HomeComponent,canActivate: [AuthguardService], children: [ { path: '', redirectTo: 'login', pathMatch: 'full' }, { path: 'listitem', component: ListitemComponent,canActivate: [AuthguardService] }, ] }, // otherwise redirect to home { path: '**', redirectTo: '/login' } ]; export const routing = RouterModule.forRoot(appRoutes); |
The angular route is used to create single page application. canActive guard implemented on the routing module. I also implement child router angularjs in this simple login page project.
A brief description:
If the user has not logged in, then the router will force redirect to login page.
Edit app.component.html and add the following code:
1 | <router-outlet></router-outlet> |
Run the program on the browser with URL localhost: 4200, if successful the system will work like the following gift image
Note: For the above code to work correctly, you should read the angular tutorial article 4 or download the complete project below
Please share this article through the share button that has been provided in the field below to open the download link
[sociallocker id=58]
Link download : https://seegatesite.com/simple-login-form-angular-4-source-code-project/
Password : seegatesite.com
[/sociallocker]
Conclusion:
As a web developer, making web applications login page on SPA (Single Page Application) is very crucial, the initial protection on login form
Some references how to create a simple login page angular 4 that might be useful to you
- jasotwatmore site : The most popular blog to learn angularjs user registration and login. He also shared the registration and login example project.
- https://angular.io/guide/router
- https://youtube.com
Unfortunately ..
It is not working
ERROR in src/app/app.routing.ts(2,35): error TS2307: Cannot find module ‘./item/listitem/listitem.component’.
hello, you can download all source project in the link above to get listitem.component.ts file. 🙂
downloaded project not showing content. Could you please share project code somewhere.
https://seegatesite.com/simple-login-form-angular-4-source-code-project/
pass: seegatesite.com
What database you have used.
mysql
it is not working
please check again
not working, no php file etc
read carefully.. you can find php file completely 🙂