Angular: Tracking an inactive user using RXJS, in-built and custom events

Sumit kumar Singh
4 min readDec 21, 2023

In modern web applications, user engagement is crucial for providing a seamless and interactive experience. One aspect of user engagement is tracking user activity to identify inactive users. In this tutorial, we will explore how to implement user inactivity tracking in an Angular application using RxJS, leveraging both in-built events and custom events.

I. Understanding User Inactivity:

User inactivity can be defined as a period during which a user does not interact with the application. Tracking this inactivity helps in various scenarios, such as optimizing resource usage, enhancing security, and providing a better user experience.

II. RxJS Overview:

RxJS, or Reactive Extensions for JavaScript, is a powerful library for handling asynchronous operations and events in a reactive manner. It is widely used in Angular applications to manage streams of data and events.

III. Using RxJS for User Inactivity Tracking:

  1. Installing RxJS:

Include RxJS in your Angular project using npm:

npm install rxjs

2. Creating an Inactivity Service:

Develop a service to encapsulate the logic for tracking user inactivity.

// inactivity.service.ts

import { Injectable } from '@angular/core';
import { Observable, fromEvent, timer } from 'rxjs';
import { mergeMap, mapTo } from 'rxjs/operators';

@Injectable({
providedIn: 'root',
})
export class InactivityService {
constructor() {}

trackInactivity(duration: number): Observable<boolean> {
const mouseMove$ = fromEvent(document, 'mousemove').pipe(mapTo(true));
const keyDown$ = fromEvent(document, 'keydown').pipe(mapTo(true));

return timer(0, duration).pipe(mergeMap(() => mouseMove$ || keyDown$));
}
}

The trackInactivity method combines mouse move and key down events to determine user activity. Adjust the duration parameter based on your application's requirements.

3. Integrating Inactivity Service:

Inject the InactivityService into a component where inactivity tracking is needed.

// app.component.ts

import { Component, OnInit } from '@angular/core';
import { InactivityService } from './inactivity.service';

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

ngOnInit(): void {
const inactivityDuration = 30000; // 30 seconds
this.inactivityService.trackInactivity(inactivityDuration).subscribe((inactive) => {
if (inactive) {
// Perform actions when user is inactive
console.log('User is inactive');
}
});
}
}

Adjust the inactivityDuration based on your application's requirements.

IV. Leveraging In-Built Events:

Angular provides in-built events that can be utilized for tracking user activity without relying solely on RxJS.

  1. Using HostListener:

The HostListener decorator can be applied to methods within a component to listen for events.

// app.component.ts

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

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
@HostListener('document:mousemove', ['$event'])
@HostListener('document:keydown', ['$event'])
onActivity(event: Event): void {
// Perform actions when user is active
console.log('User is active');
}
}

2. Using Renderer2:

The Renderer2 service allows programmatic access to the DOM and can be used to listen for events.

// app.component.ts

import { Component, Renderer2, ElementRef, OnInit } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
constructor(private renderer: Renderer2, private el: ElementRef) {}

ngOnInit(): void {
this.renderer.listen('document', 'mousemove', () => {
// Perform actions when user is active
console.log('User is active');
});
}
}

V. Implementing Custom Events:

Custom events can be defined and triggered within an Angular application to handle specific user interactions.

  1. Creating a Custom Event Service:

Develop a service to manage custom events.

// custom-event.service.ts

import { Injectable, EventEmitter } from '@angular/core';

@Injectable({
providedIn: 'root',
})
export class CustomEventService {
public userActivityEvent: EventEmitter<void> = new EventEmitter<void>();

constructor() {}

triggerUserActivityEvent(): void {
this.userActivityEvent.emit();
}
}

2. Utilizing Custom Events:

Integrate the custom event service into components where user activity tracking is required.

// app.component.ts

import { Component, OnInit } from '@angular/core';
import { CustomEventService } from './custom-event.service';

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

ngOnInit(): void {
this.customEventService.userActivityEvent.subscribe(() => {
// Perform actions when user is active
console.log('User is active');
});
}
}

Conclusion:

In this comprehensive tutorial, we explored multiple approaches to track user inactivity in an Angular application. Leveraging RxJS, in-built events, and custom events provides developers with flexibility based on their specific use cases. Whether using a dedicated service with RxJS or tapping into Angular’s in-built event handling mechanisms, the goal remains the same: to enhance user experience by responding to user activity or inactivity appropriately. Consider the specific requirements of your application and choose the method that best fits your needs for tracking user engagement.

Thanks for reading!

I hope, you found this article useful. If you have any questions or suggestions, please leave comments. Your feedback helps me to become better.

Don’t forget to subscribe⭐️

--

--

Sumit kumar Singh

YouTube: https://www.youtube.com/@tech..Design/ 📚 HTML,Angular, React,and JavaScript 🧑‍💻 Tips & tricks on Web Developing 👉 FULL STACK DEVELOPER