Angular 8 User Registration and Login Example and Tutorial

In this tutorial, we’ll create an angular application to understand how to build a simple user registration and login system using Angular 8, TypeScript and webpack 4.

Below are the requirements for creating the CRUD on MEAN

  • Node.js

  • Angular CLI

  • Angular 8

  • Mongodb

  • IDE or Text Editor

We assume that you have already available the above tools/frameworks and you are familiar with all the above that what individually actually does.

Have a look at the project stucture:

So now we will proceed step by step to achieve the task.

Auth Guard

The auth guard is used to prevent unauthenticated users from accessing restricted routes.

import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from'@angular/router';
 
import { AuthenticationService } from '../_services';
 
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(
private router: Router,
private authenticationService: AuthenticationService
) {}
 
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
const currentUser = this.authenticationService.currentUserValue;
if (currentUser) {
// authorised so return true
return true;
}
 
// not logged in so redirect to login page
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url }});
return false;
}
}

User Model

The user model is a class inside the _modals folder that defines the properties of a user form.

export class User {
firstName: string;
lastName: string;
email: string;
phone: number;
password: string;
}

Authentication Service

This is a file under _services folder, It is having functionalities of login and log out of user into the application. The logged in user details are stored in local storage so the user will stay logged in if they refresh the browser and also between browser sessions until they log out.

 
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BehaviorSubject, Observable } from 'rxjs';
import { map } from 'rxjs/operators';
 
import { User } from '../_models';
 
@Injectable({ providedIn: 'root' })
export class AuthenticationService {
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
 
constructor(private http: HttpClient) {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
}
 
public get currentUserValue(): User {
return this.currentUserSubject.value;
}
 
login(email: string, password: string) {
return this.http.post<any>(`auth/login`, { email, password })
.pipe(map(user => {
if (user && user.token) {
// store user details in local storage to keep user logged in
localStorage.setItem('currentUser', JSON.stringify(user.result));
this.currentUserSubject.next(user);
}
 
return user;
}));
}
 
logout() {
// remove user data from local storage for log out
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
}

User Service

This service is having methods for all the basic user HTTP call like reset password, change password, forgot password request etc.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
 
import { User } from '../_models/user';
 
@Injectable({ providedIn: 'root' })
export class UserService {
constructor(private http: HttpClient) { }
 
register(user: User) {
return this.http.post(`auth/register`, user);
}
 
}

Interceptor Service

Interceptors provide a mechanism to intercept and/or mutate outgoing requests or incoming responses. They are very similar to the concept of middleware with a framework like Express, except for the frontend. Interceptors can be really useful for features like caching and logging

import {
HttpInterceptor,
HttpRequest,
HttpHandler,
HttpEvent
} from "@angular/common/http";
import { Observable } from "rxjs";
import { Injectable } from "@angular/core";
import { environment } from "../../environments/environment";
@Injectable()
export class InterceptorService implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
let reqUrl = environment.apiBaseUrl;
req = req.clone({
headers: req.headers.set(
"Authorization",
"Bearer " + localStorage.getItem("token")
),
url: reqUrl +""+ req.url
});
return next.handle(req);
}
}

Home Component Template

Code for basic welcome message

<h1>Hi {{currentUser.firstName}}!</h1>

<p>Welcome to home page!!</p>

Home Component Ts File

This file contains basic class structure for now with currentUser variable which is receiving value from local storage.

import { Component, OnInit } from '@angular/core';
 
@Component({
selector: 'app-home',
templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
public currentUser;
constructor() {
this.currentUser = localStorage.getItem('currentUser')? JSON.parse(localStorage.getItem('currentUser')) : '';
}
 
ngOnInit() {
 
}
}

Login Component Template

A basic form with email and password field with basic validation, And after submit onFormSubmit method will be called inside ts file of the component.

<h3>User Login</h3>
<form [formGroup]="loginForm" (ngSubmit)="onFormSubmit()">
<div class="form-group">
<label for="email">Email</label>
<input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && fval.email.errors }" placeholder="Enter email here"/>
<div *ngIf="submitted && fval.email.errors" class="invalid-feedback">
<div *ngIf="fval.email.errors.required">Email is required</div>
<div *ngIf="fval.email.errors.email">Enter valid email address</div>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && fval.password.errors }" placeholder="Enter password here" />
<div *ngIf="submitted && fval.password.errors" class="invalid-feedback">
<div *ngIf="fval.password.errors.required">Password is required</div>
</div>
</div>
<div class="form-group">
<button [disabled]="loading" class="btn btn-primary">
<span *ngIf="loading" class="spinner-border spinner-border-sm mr-1"></span>
Login
</button>
<a routerLink="/register" class="btn btn-link">Register</a>
</div>
</form>

Login Component Ts File

File with the code to send login request from this component to authentication service. The toaster has been used to show alerts to the user.

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
 
import { AuthenticationService } from '../_services';
 
@Component({
selector: 'app-login',
templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
loading = false;
submitted = false;
returnUrl: string;
 
constructor(
private formBuilder: FormBuilder,
private route: ActivatedRoute,
private router: Router,
private authenticationService : AuthenticationService,
private toastr: ToastrService
) { }
 
ngOnInit() {
this.loginForm = this.formBuilder.group({
email: ['', Validators.required],
password: ['', Validators.required]
});
 
}
 
// for accessing to form fields
get fval() { return this.loginForm.controls; }
 
onFormSubmit() {
this.submitted = true;
if (this.loginForm.invalid) {
return;
}
 
this.loading = true;
this.authenticationService.login(this.fval.email.value, this.fval.password.value)
.subscribe(
data => {
this.router.navigate(['/']);
},
error => {
this.toastr.error(error.error.message, 'Error');
this.loading = false;
});
}
}

Register Component Template

File with fields of the registration of the new user in the application.

<h3>User Registration</h3>
<form [formGroup]="registerForm" (ngSubmit)="onFormSubmit()">
<div class="form-group">
<label for="firstName">First Name</label>
<input type="text" formControlName="firstName" class="form-control" [ngClass]="{ 'is-invalid': submitted && fval.firstName.errors }" placeholder="Enter First Name here"/>
<div *ngIf="submitted && fval.firstName.errors" class="invalid-feedback">
<div *ngIf="fval.firstName.errors.required">First Name is required</div>
</div>
</div>
 
<div class="form-group">
<label for="lastName">Last Name</label>
<input type="text" formControlName="lastName" class="form-control" placeholder="Enter Last Name here"/>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" formControlName="email" class="form-control" [ngClass]="{ 'is-invalid': submitted && fval.email.errors }" placeholder="Enter email here"/>
<div *ngIf="submitted && fval.email.errors" class="invalid-feedback">
<div *ngIf="fval.email.errors.required">Email is required</div>
<div *ngIf="fval.email.errors.email">Enter valid email address</div>
</div>
</div>
<div class="form-group">
<label for="email">Phone</label>
<input type="text" formControlName="phone" class="form-control" [ngClass]="{ 'is-invalid': submitted && fval.phone.errors }" placeholder="Enter Phone here"/>
<div *ngIf="submitted && fval.phone.errors" class="invalid-feedback">
<div *ngIf="fval.phone.errors.required">Phone is required</div>
</div>
</div>
 
<div class="form-group">
<label for="email">Password</label>
<input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && fval.password.errors }" placeholder="Enter Password here"/>
<div *ngIf="submitted && fval.password.errors" class="invalid-feedback">
<div *ngIf="fval.password.errors.required">Password is required</div>
<div *ngIf="fval.password.errors.minlength">Password must be at least 6 characters</div>
</div>
 
</div>
 
<div class="form-group">
<button [disabled]="loading" class="btn btn-primary">
<span *ngIf="loading" class="spinner-border spinner-border-sm mr-1"></span>
Register
</button>
<a routerLink="/login" class="btn btn-link">Login to continue</a>
</div>
</form>

Register Component Ts File

File with the logical part of the registration process. The registerForm: FormGroup object defines the form controls and validators and is used to access data entered into the form.

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
 
import { UserService } from '../_services/user.service';
@Component({
selector: 'app-register',
templateUrl: './register.component.html'
})
export class RegisterComponent implements OnInit {
 
constructor(
private formBuilder: FormBuilder,
private router: Router,
private userService: UserService,
private toastr: ToastrService
) { }
registerForm: FormGroup;
loading = false;
submitted = false;
 
ngOnInit() {
this.registerForm = this.formBuilder.group({
firstName: ['', Validators.required],
lastName: ['', Validators.required],
phone: ['', Validators.required],
email: ['', [Validators.required,Validators.email]],
password: ['', [Validators.required, Validators.minLength(6)]]
});
}
 
get fval() { return this.registerForm.controls; }
 
onFormSubmit(){
this.submitted = true;
// return for here if form is invalid
if (this.registerForm.invalid) {
return;
}
this.loading = true;
this.userService.register(this.registerForm.value).subscribe(
(data)=>{
alert('User Registered successfully!!');
this.router.navigate(['/login']);
},
(error)=>{
this.toastr.error(error.error.message, 'Error');
this.loading = false;
}
)
 
}
 
}

App Component Template

The app component template is the root component template of the application, it contains a router-outlet directive for displaying the contents of each view based on the current route.

<!-- main app container -->
<div class="jumbotron">
<a *ngIf="currentUser" class="nav-item nav-link" style="cursor:pointer"(click)="logout()">Logout</a>
<div class="container">
<div class="row">
<div class="col-md-4 offset-md-4">
<router-outlet></router-outlet>
</div>
</div>
</div>
</div>

App Component Ts File

The app component is the root component of the application, it defines the root tag of the app as <app></app> with the selector property of the @Component decorator.

import { Component } from '@angular/core';
import { Router } from '@angular/router';
 
import { AuthenticationService } from './_services';
import { User } from './_models';
 
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
currentUser: User;
 
constructor(
private router: Router,
private authenticationService: AuthenticationService
) {
this.authenticationService.currentUser.subscribe(x => this.currentUser = x);
}
 
logout() {
this.authenticationService.logout();
this.router.navigate(['/login']);
}
 
}

App Routing File

Routing for the Angular app is configured as an array of Routes, each component is mapped to a path so the Angular Router knows which component to display based on the URL in the browser address bar. The home route is secured by passing the AuthGuard to the canActivate property of the route.

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { AuthGuard } from './_helpers/auth.guard';
 
/**Componenets */
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { HomeComponent } from './home/home.component';
 
const routes: Routes = [
{ path: '', component: HomeComponent, canActivate: [AuthGuard] },
{
path: 'login',
component: LoginComponent
},
{
path: 'register',
component: RegisterComponent
},
{ path: '**', redirectTo: '' }
 
];
 
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }

App Module

app.module.ts file with all the components, modules, services imported and bootstrapped here in this file. It define the root module of the application along with metadata about the module

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
 
import { ToastrModule } from 'ngx-toastr';
// services
import { InterceptorService } from './_services/interceptor.service';
import { UserService } from './_services/user.service';
 
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { RegisterComponent } from './register/register.component';
import { HomeComponent } from './home/home.component';
 
@NgModule({
declarations: [
AppComponent,
LoginComponent,
RegisterComponent,
HomeComponent
],
imports: [
BrowserModule,
AppRoutingModule,
ReactiveFormsModule,
HttpClientModule,
BrowserAnimationsModule, // required animations module
ToastrModule.forRoot()
],
providers: [UserService,{ provide: HTTP_INTERCEPTORS, useClass: InterceptorService, multi: true}], //
bootstrap: [AppComponent]
})
export class AppModule { }

Server

Please find the detailed blog on creating server for user registration and login application Start Creating APIs in Node.js with Async/Await

Conclusion

In this demo, we understand the User Registration and login in Angular 8. You can find other demos at Angular sample application

That’s all for now. Thank you for reading and I hope this post will be very helpful for Angular 8 User Registration and Login Example and Tutorial.

Originally published by Suraj Roy at jsonworld.com

#angular #web-development

What is GEEK

Buddha Community

Angular 8 User Registration and Login Example and Tutorial

I am Developer

1610191977

Angular 11 Google Social Login Example Tutorial

Angular 9/10/11 social login with google using angularx-social-login library example. In this tutorial, i will show you step by step on how to implement google social login in angular 11 app.

And also, this tutorial will show you How to login into Angular 10/11 application with google using angularx-social-login library in angular 11 app.

Google Login Integration In Angular 11 App

  • Step 1 - Create New Angular App
  • Step 2 - Install Social Login Library
  • Step 3 - Add Code on App.Module.ts File
  • Step 4 - Add Code on View File
  • Step 5 - Add Code On App.Component ts File
  • Step 6 - Start the Angular Google Login App

https://www.tutsmake.com/angular-11-google-social-login-example/

#angular 11 google login #angular 11 social-login example #login with google button angular 8/9/10/11 #angular 10/11 login with google #angular 10 social google login #angular social login google

I am Developer

1610191977

Angular 11 Google Social Login Example

Angular 9/10/11 social login with google using angularx-social-login library example. In this tutorial, i will show you step by step on how to implement google social login in angular 11 app.

And also, this tutorial will show you How to login into Angular 10/11 application with google using angularx-social-login library in angular 11 app.

Google Login Integration In Angular 11 App

  • Step 1 - Create New Angular App
  • Step 2 - Install Social Login Library
  • Step 3 - Add Code on App.Module.ts File
  • Step 4 - Add Code on View File
  • Step 5 - Add Code On App.Component ts File
  • Step 6 - Start the Angular Google Login App

https://www.tutsmake.com/angular-11-google-social-login-example/

#angular 11 google login #angular 11 social-login example #login with google button angular 8/9/10/11 #angular 10/11 login with google #angular 10 social google login #angular social login google

I am Developer

1609902140

Angular 11 Facebook Social Login Example

Angular 9/10/11 social login with facebook using angularx-social-login library example. In this tutorial, i would love to show you how to integrate facebook social login in angular 11 app.

And you will learn how to add facebook social login button with angular reactive login form.

Angular 11 Social Login with Facebook Tutorial

  • Step 1 - Create New Angular App
  • Step 2 - Install Social Login Library
  • Step 3 - Add Code on App.Module.ts File
  • Step 4 - Add Code on View File
  • Step 5 - Add Code On App.Component ts File
  • Step 6 - Start the Angular Facebook Login App

https://www.tutsmake.com/angular-11-facebook-login-tutorial-example/

#angular 11 facebook login #angular 11 social-login example #login with facebook button angular 8/9/10/11 #angular 10/11 login with facebook #angular 10 social facebook login #angular social login facebook

I am Developer

1617089618

Laravel 8 Tutorial for Beginners

Hello everyone! I just updated this tutorial for Laravel 8. In this tutorial, we’ll go through the basics of the Laravel framework by building a simple blogging system. Note that this tutorial is only for beginners who are interested in web development but don’t know where to start. Check it out if you are interested: Laravel Tutorial For Beginners

Laravel is a very powerful framework that follows the MVC structure. It is designed for web developers who need a simple, elegant yet powerful toolkit to build a fully-featured website.

Recommended:-Laravel Try Catch

#laravel 8 tutorial #laravel 8 tutorial crud #laravel 8 tutorial point #laravel 8 auth tutorial #laravel 8 project example #laravel 8 tutorial for beginners

Clara  Gutmann

Clara Gutmann

1598716260

Angular 8 CRUD Example | Angular 8 Tutorial For Beginners

Angular 8 CRUD is a basic operation to learn Angular from scratch. We will learn how to build a small web application that inserts, read data, update and delete data from the database. You will learn how to create a MEAN Stack web application. In this Angular 8 Tutorial Example, you will learn a new framework by building a crud application.

New features of Angular 8

You check out the new features in brief on my  Angular 8 New Features post.

I have designed this Angular 8 CRUD Tutorial, especially for newcomers, and it will help you to up and running with the latest version of Angular, which is right now 8.

#angular #angular 8 #angular 8 crud