Handling Idle State for Users in Angular
1 min readSep 18, 2023
I found lots of lib to handle idle state but I thought why we should use any externals lib if we can do it in simplest way I achieved in one of use case so thought I should share this with entire world so people can help from it.
Step 1: Setting up the Angular Project:
setup the project with the help of angular cli
Step 2: Importing Necessary Modules:
import { Component, HostListener } from '@angular/core';
import { Subject } from 'rxjs';
Step 3: Creating the AppComponent:
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
userActivity: any;
userInactive: Subject<any> = new Subject();
constructor() {
this.setTimeout();
this.userInactive.subscribe(() => console.log('user has been inactive for 3s'));
}
Step 4: Implementing the setTimeout
Function:
setTimeout() {
this.userActivity = setTimeout(() => this.userInactive.next(undefined), 10000);
}
Step 5: Using the @HostListener
:
@HostListener('window:mousemove') refreshUserState() {
clearTimeout(this.userActivity);
this.setTimeout();
}
Final app.components.ts
import { Component, HostListener } from '@angular/core';
import { Subject } from 'rxjs';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
userActivity: any;
userInactive: Subject<any> = new Subject();
constructor() {
this.setTimeout();
this.userInactive.subscribe(() => console.log('user has been inactive for 3s'));
}
setTimeout() {
this.userActivity = setTimeout(() => this.userInactive.next(undefined), 10000);
}
@HostListener('window:mousemove') refreshUserState() {
clearTimeout(this.userActivity);
this.setTimeout();
}
}