How to check user inactivity in Angular?

Lets say you want to alert the user if they remain inactive for a long time.

Or you want to log the user out if they are inactive for a long time.

How can you do that in angular?

The below algorithm can be followed to achieve that:

STEP 1:

Define user inactivity :

  1. User does not press any key for the specified time.
  2. User does not click the mouse on the app for the specified time.

I have considered these two. In app.component.ts add the following:

  @HostListener('window:keydown')
  @HostListener('window:mousedown')
   checkUserActivity() {
   
//check below steps for the code to be entered here.
  }

STEP 2:

Lets create an Observable in Angular code. This will look for user inactivity and then alert the user .

userInactive: Subject<any> = new Subject();

Lets create a method checkTimeOut() which will initialize javascript timer using the inbuilt setTimeout method .

Lets invoke this in the constructor

checkTimeOut() {


    this.timeoutId = setTimeout(

      () => this.userInactive.next("User has been inactive for 5 seconds"), 5000
    );

    
  }

 constructor(){

    this.checkTimeOut();
   
  
  );

In the above code timoutId is a random id returned by setTimeout() javascript method. This will be used to cancel the timer if user clicks the mouse or presses any key and then start the timer again(shown later below) .

() => this.userInactive.next(“User has been inactive for 5 seconds”) is a javascript function which will be called by setTimeout() function every 5 seconds.

This will activate the observable ‘userInactive’.

STEP 3:

Subscribe for the observable inside the constructor

 constructor() {

    this.checkTimeOut();
    this.userInactive.subscribe((message) => {

      alert(message);
//or call log out functionality as required 


    }

    );


  }

STEP 4:

Cancel the timer if user does any activity and start it again

  @HostListener('window:keydown')
  @HostListener('window:mousedown')
  checkUserActivity() {

    clearTimeout(this.timeoutId);

    this.checkTimeOut();
  }

The entire code is given below :

import { Component, HostListener } from '@angular/core';

import { Subject } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {


  timeoutId;
  userInactive: Subject<any> = new Subject();

 constructor() {

    this.checkTimeOut();
    this.userInactive.subscribe((message) => {

      alert(message);
    }
    );
  }

  checkTimeOut() {

    this.timeoutId = setTimeout(

      () => this.userInactive.next("User has been inactive for 5 seconds"), 5000
    );


  }

  @HostListener('window:keydown')
  @HostListener('window:mousedown')
  checkUserActivity() {

    clearTimeout(this.timeoutId);

    this.checkTimeOut();
  }
}

That’s it!

The above algorithm can be simplified if you just need to show an alert message and do not want to log out the user or do not want to refer to any component variables or methods. The Observable pattern logic can be skipped here.

Here is the code :

import { Component, HostListener } from '@angular/core';

import { Subject } from 'rxjs';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  
  timeoutId;

  constructor(){

    this.checkTimeOut();
 
  }


  checkTimeOut() {

    this.timeoutId = setTimeout(

     function(){
      
 
        alert("User has been inactive for a long time")}, 5000
    );

    
  }

  @HostListener('window:keydown')
  @HostListener('window:mousedown')
   checkUserActivity() {
   
    clearTimeout(this.timeoutId);

    this.checkTimeOut();
  }

 

}

The only reason I have used observable in the first case is that you cannot refer to any variable or method of the component , inside this javascript method :

 function(){

//cant refer to component variables or methods - scope is limited
    alert("User has been inactive for a long time")
}

Hope that helps.


Posted

in

,

by

Comments

3 responses to “How to check user inactivity in Angular?”

  1. Christian Avatar
    Christian

    Excelente, solo una pregunta , como controlo el cierre del cuadro de diálogo que se ejecuta en otras pestañas

    1.  Avatar
      Anonymous

      logre encontrar como:

      ngOnDestroy(): void {
      this.userInactive.unsubscribe();
      }

      1. Vijay SRJ Avatar
        Vijay SRJ

        Can you please say it in English

Leave a Reply to AnonymousCancel reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading