• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
seegatesite header

Seegatesite.com

Seegatesite.com - Programming Tutorial , Sharing , How and Learn Together

  • TOOLS
    • Bootstrap Navbar Online Generator
    • Customize Sidebar Menu Bootstrap 3
    • Bootstrap Demo
  • ADVERTISE
  • CATEGORIES
    • Android
    • Blogging Tips
    • Database
    • CSS
    • Info Gadget
    • Javascript
    • Linux
    • PHP
    • Various
    • WordPress
  • Q&A
  • PHP
  • JAVASCRIPT
  • JQUERY
  • ANGULAR
  • WORDPRESS
  • SEO
  • REACT
🏠 » Javascript » Simple Login Form Angular 4 Tutorial For Beginner

Simple Login Form Angular 4 Tutorial For Beginner

By Sigit Prasetya Nugroho ∙ September 26, 2017 ∙ Javascript ∙ 10 Comments

Share : TwitterFacebookTelegramWhatsapp

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

  • 1 Getting Started
  • 2 Login Form App Angular 4 For Beginner
    • 2.1 Data service
    • 2.2 Authguard Service
    • 2.3 Login Component.
    • 2.4 Home Component
    • 2.5 Conclusion:
    • 2.6 So my article on how to create simple login form and authentication on angular 4

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

Related Articles :

  • Trick To Redirect New Window Or Tab With Post Method On Angular 5
  • Tutorial To Change Date Format Ng-bootstrap Datepicker Angular 5
  • Tutorial Simple CRUD Angular 5 And Lumen 5.6 For Beginners

Pos Mysql Database Simple Login Form Angular 4

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.

Change Database Configuration On Dbconn.php File Min

If the above preparations have been completed, the next step We will make the main application.

Login Form Angular 4 Tutorial For Beginner Min

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 url
    1
    private 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

Home Component Angular 4 Login Form Tutorial

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

Login Form Angular 4 Tutorial 2

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

So my article on how to create simple login form and authentication on angular 4

Another Javascript Related Post :

  • Tutorial Create Simple POS Using ReactJS And Laravel Lumen Part 1
  • Adept Using Datatables Plugin In 10 Minutes For Beginners (Tutorial)
  • The Using Of Reactstrap And React-Table, Suitable For Beginners
  • Tutorial Create Simple Block UI Using React JS
  • How To Implement Login Page And Protected Route ReactJS
  • Complete Tutorial React Router Dom For Beginners (Easy-To-Understand)

Avatar for Sigit Prasetya Nugroho

About Sigit Prasetya Nugroho

This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Reader Interactions

Comments

  1. Avatar for anananan says

    February 17, 2018 at 2:41 am

    Unfortunately ..

    It is not working
    ERROR in src/app/app.routing.ts(2,35): error TS2307: Cannot find module ‘./item/listitem/listitem.component’.

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      February 17, 2018 at 3:39 am

      hello, you can download all source project in the link above to get listitem.component.ts file. 🙂

      Reply
  2. Avatar for rahulrahul says

    May 1, 2018 at 2:50 pm

    downloaded project not showing content. Could you please share project code somewhere.

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      May 5, 2018 at 4:30 am

      https://seegatesite.com/simple-login-form-angular-4-source-code-project/

      pass: seegatesite.com

      Reply
  3. Avatar for RashiRashi says

    May 10, 2018 at 6:26 am

    What database you have used.

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      May 15, 2018 at 1:35 am

      mysql

      Reply
  4. Avatar for amil hassanamil hassan says

    August 20, 2018 at 12:08 pm

    it is not working

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      August 23, 2018 at 6:39 am

      please check again

      Reply
  5. Avatar for GirishGirish says

    November 7, 2018 at 11:08 am

    not working, no php file etc

    Reply
    • Avatar for Sigit Prasetya NugrohoSigit Prasetya Nugroho says

      November 12, 2018 at 6:08 am

      read carefully.. you can find php file completely 🙂

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Welcome to my Home,

Avatar for Sigit Prasetya NugrohoThis site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.



Popular Articles

Checked checkbox AdminLTE Bootstrap in Jquery

November 4, 2014 By Sigit Prasetya Nugroho 7 Comments

Simple create date format validation with jqueryUI

December 21, 2014 By Sigit Prasetya Nugroho Leave a Comment

Create Simple Progress Bar for Fake Online Generator with Jquery

January 10, 2015 By Sigit Prasetya Nugroho Leave a Comment

22+ Coolest Free Jquery Plugin For Premium Theme

October 3, 2015 By Sigit Prasetya Nugroho Leave a Comment

Easy Build Your Anti Copy Paste Plugin

October 6, 2015 By Sigit Prasetya Nugroho Leave a Comment

Popular Tags

adminlte (15) adsense (13) adsense tips (4) affiliate amazon (13) amazon (12) Android (8) angular (16) angular 4 (12) angular 5 (4) asin grabber (3) Bootstrap (27) codeigniter (5) create wordpress theme (5) crud (8) css (6) free wordpress theme (7) google adsense (4) imacros (4) increase traffic (6) jquery (34) laravel (10) laravel 5 (5) learn android (5) lumen api (4) modal dialog (5) mysql (6) nodeJs (4) optimize seo (4) pdo (6) php (30) plugin (53) pos (8) Publisher Tips (5) react (4) Reactjs (7) SEO (37) theme (17) tutorial angular (5) tutorial angular 4 (6) tutorial javascript (10) tutorial javascript beginners (4) twitter (3) wordpress (18) wordpress plugin (13) XMLRPC (5)




  • About
  • Contact Us
  • Disclaimer
  • Privacy Policy
  • Terms and Conditions

©2021 Seegatesite.com