How to Redirect Users to Last Active Page before Logout in Angular ?
Last Updated :
26 Jul, 2024
Redirecting the users to the last active page before logout after they log in is the most common feature or functionality in web applications. This functionality enhances the user’s experience by saving their session state and also enables them to resume their activities seamlessly after they log in. In the article, we will see the practical implementation for redirecting users to the last active page before logout after login
Prerequisites:
Before we start, we need to install and configure the tools below to create the Angular application:
- Nodejs and npm
- Angular CLI
- An IDE ( VS Code )
Steps to redirect users to the last active page in Angular Application
The following steps will be implemented to redirect users to the last active page before logout after login in an Angular App:
Step 1: Create an Angular application
Let’s start by using the Angular CLI to generate our base application structure, with routing and a CSS stylesheet.
> ng new AngularApp
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? CSS
. . .
CREATE AngularApp/src/app/app.component.css (0 bytes)
Packages installed successfully.
Successfully initialized git.
Step 2: Creating Directory Structure
Make the directory structure according to the below-added image:

Step 3: Create a Dashboard Component
After the successful creation of the Angular App, now, create the dashboard component in the src/app/components directory by executing the below command and adding the below code in the respective files.
ng generate component dashboard
HTML
<!-- dashboard.component.html -->
<h2>Welcome to the Dashboard!</h2>
<p>
Click the button to simulate a user logout.
</p>
<button (click)="logout()">
Logout
</button>
JavaScript
// dashboard.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { LastActivePageService }
from '../../services/last-active-page.service';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent {
constructor(private router: Router,
private lastActivePageService: LastActivePageService) { }
logout(): void {
// Store the current URL before logout
this.lastActivePageService.storeLastActivePage(this.router.url);
this.router.navigateByUrl('/login');
}
}
Step 4: Create a Home Component
Create the home component in the src/app/components directory by executing the below command and adding the below code in the respective files.
ng generate component home
HTML
<!-- home.component.html -->
<h1>Welcome to the Home Page</h1>
<p>
Click the button to simulate a
user logout from the home page.
</p>
<button (click)="logout()">Logout</button>
JavaScript
// home.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { LastActivePageService }
from '../../services/last-active-page.service';
@Component({
selector: 'app-home-page',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomePageComponent {
constructor(private router: Router,
private lastActivePageService: LastActivePageService) { }
logout(): void {
// Store the current URL before logout
this.lastActivePageService.storeLastActivePage(this.router.url);
this.router.navigateByUrl('/login');
}
}
Step 5: Create a Login Component
Create the login component in the src/app/components directory by executing the below command and adding the below code in the respective files.
ng generate component login
HTML
<!-- login.component.html -->
<h2>Login</h2>
<form (submit)="login()">
<div>
<label for="username">Username:</label>
<input type="text"
id="username"
[(ngModel)]="username"
name="username" required>
</div>
<div>
<label for="password">Password:</label>
<input type="password"
id="password"
[(ngModel)]="password"
name="password" required>
</div>
<button type="submit">Login</button>
</form>
JavaScript
// login.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { LastActivePageService }
from '../../services/last-active-page.service';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
username: string = '';
password: string = '';
constructor(private router: Router,
private lastActivePageService: LastActivePageService) { }
login(): void {
const enteredUsername = this.username.trim();
const enteredPassword = this.password.trim();
if (enteredUsername === 'admin' && enteredPassword === 'admin') {
const lastActivePage =
this.lastActivePageService.getLastActivePage();
if (lastActivePage) {
this.router.navigateByUrl(lastActivePage);
} else {
// If no last active page is available,
// redirect to the default dashboard page.
this.router.navigateByUrl('/dashboard');
}
} else {
console.log('Login failed. Invalid credentials.');
}
}
}
Step 6: Create the Last Active Page
Create the last-active-page.service.ts file in the src/app/services directory and add the below code to it.
JavaScript
// last-active-page.service.ts
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LastActivePageService {
private lastActivePage: string | null = null;
constructor() { }
storeLastActivePage(url: string): void {
this.lastActivePage = url;
}
getLastActivePage(): string | null {
return this.lastActivePage;
}
clearLastActivePage(): void {
this.lastActivePage = null;
}
}
Step 7: Configuring App Component Files
Now, configure the app files by adding the proper route and rendering. Add the below code in the respective files.
HTML
<!--app.component.html-->
<router-outlet></router-outlet>
JavaScript
// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes }
from '@angular/router';
import { LoginComponent }
from './components/login/login.component';
import { DashboardComponent }
from './components/dashboard/dashboard.component';
import { HomePageComponent }
from './components/home/home.component';
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'dashboard', component: DashboardComponent },
{ path: 'home', component: HomePageComponent },
// Default route to home page
{ path: '', redirectTo: '/home', pathMatch: 'full' },
// Redirect any other route to home page
{ path: '**', redirectTo: '/home' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
JavaScript
// app.module.ts
import { NgModule }
from '@angular/core';
import { BrowserModule }
from '@angular/platform-browser';
import { FormsModule }
from '@angular/forms';
import { AppRoutingModule }
from './app-routing.module';
import { AppComponent }
from './app.component';
import { LoginComponent }
from './components/login/login.component';
import { DashboardComponent }
from './components/dashboard/dashboard.component';
import { HomePageComponent }
from './components/home/home.component';
import { LastActivePageService }
from './services/last-active-page.service';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
DashboardComponent,
HomePageComponent
],
imports: [
BrowserModule,
FormsModule,
AppRoutingModule
],
providers: [LastActivePageService],
bootstrap: [AppComponent]
})
export class AppModule { }
JavaScript
//app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {}
Step 8: Main File
HTML
<!--index.html-->
<!DOCTYPE html>
<html>
<head>
<title>My Angular App</title>
<base href="/">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<app-root></app-root>
</body>
</html>
JavaScript
// main.ts
import { platformBrowserDynamic }
from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.error(err));
Step 9: Dependency files
{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"sourceMap": true,
"declaration": false,
"downlevelIteration": true,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "ES2022",
"module": "ES2022",
"useDefineForClassFields": false,
"lib": [
"ES2022",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}
{
"name": "angular-app",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^16.1.0",
"@angular/common": "^16.1.0",
"@angular/compiler": "^16.1.0",
"@angular/core": "^16.1.0",
"@angular/forms": "^16.1.0",
"@angular/platform-browser": "^16.1.0",
"@angular/platform-browser-dynamic": "^16.1.0",
"@angular/router": "^16.1.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.13.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "^16.1.5",
"@angular/cli": "~16.1.5",
"@angular/compiler-cli": "^16.1.0",
"@types/jasmine": "~4.3.0",
"jasmine-core": "~4.6.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.1.3"
}
}
Step 10: Run the application
Finally, we are ready to test our application. Run the application with the command below:
> ng serve
Browser application bundle generation complete.
. . .
** Angular Live Development Server is listening on localhost:4200,
open your browser on http://localhost:4200/ **
√ Compiled successfully.
Explanation:
- After logout, the user is redirected to the login page.
- When the user enters the login credentials and clicks the “Login” button, the application checks if there is any stored last active page before logout.
- If there is a last active page, the user is redirected to that page (either home page or dashboard) as per the last visited page before logout.
- If there is no last active page (i.e., the user directly accessed the login page), the user is redirected to the default dashboard page.
Output:
Similar Reads
How to force redirect to a particular route in angular?
Introduction: We can use the property binding concept and we can pass query parameters to routerLink. Using Property binding we can bind queryParams property and can provide the required details in object. Property Binding: It is a concept where we use square bracket notation to bind data to Documen
3 min read
How to Configure Where to Redirect After a Log Out in Django?
One common requirement in many Django applications is redirecting users to a specific page after they log out. By default, Django redirects users to the login page, but this can be customized to suit our needs. There are two general methods to redirect users to the specific URL after they log out. C
6 min read
How to Redirect to Another Page in VueJS ?
Redirecting to another page is a common requirement in web development especially in the Vue.js applications. It allows users to navigate seamlessly between the different views or pages within the application. These are the following methods: Table of Content Using router.push() methodUsing the rout
2 min read
How to redirect a page to another page in HTML ?
Redirecting a page in HTML involves sending users to a different web page automatically or upon interaction. This can be achieved using the anchor tag's href attribute or the meta tag with the http-equiv attribute set to refresh and the content attribute specifying the time delay and destination URL
3 min read
How to Redirect 404 errors to a page in Express.js ?
Express Js is a web application framework based on Node.js web server functionality that helps us to create web servers with lesser complexity and in a well-organized manner. Express provides routing services that help us in creating application endpoints that respond based on the HTTP request metho
3 min read
How to determine active route in AngularJS ?
In this article, we will see how to determine the active route in AngularJS, along with understanding the basic implementation through the example. Approach: To determine which is the active route at any moment in AngularJS this can be achieved by using $on() & $location.path() method. An event
2 min read
How to use $rootScope to store variables in Angular ?
In Angular, the $rootScope is the service that is the top-level for all the controllers in the Angular application. This exists over the entire application lifecycle and can also be used to store the variables that need to be accessed globally. $rootScope is a singleton object that is across the ent
4 min read
How to Get Page Load Time in Angular?
In web development, performance is the most important thing. Users expect fast and responsive web applications and even minor delays can impact user experience and satisfaction. Monitoring page load time is important for identifying performance bottlenecks and optimizing the user experience. In this
5 min read
How to Redirect to Another Page After 5 Seconds using jQuery ?
In this article, we will learn, how to redirect to another page or URL after a specified time in jQuery. The built-in function used for performing the action is as follows. The setTimeout(callback, delay) function takes two parameters a callback and a time in milliseconds. When this method is called
1 min read
How to reload or re-render the entire page using AngularJS?
While working with AngularJS we might come across a time when we want our user to switch contexts and re-render everything again.AngularJS provides a method by which we can re-render or even reload the entire page. So in this article, we will see how we can reload the route instead of just reloading
2 min read