Global Page Load event Application wide Applicable to All components

In angular application, is it possible to define a global Page Load event application wide, which is applicable to all the components?

I have a angular application having 50 components. Each component has it’s dedicated url. But all the components are independent and do not extend a common parent base component. I am tasked to add some analytics logic on each page/component visit. I was wondering if there is a way, we can write one page load event application wide, which is applicable to all the components. So that instead of modifying 50 components, is it possible to add the event application wide, and declare it as default.

>Solution :

Yes, it is possible to define a global page load event in an Angular application. You can use the Angular Router to listen for the navigation events and trigger your analytics logic.

In your app.module.ts file, you can subscribe to the NavigationEnd event of the Router and execute your analytics code. Here’s an example:

import { Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';

export class AppModule {
  constructor(private router: Router) {
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe(event => {
        // your analytics logic here
        console.log('Page loaded: ', event.url);

If you need any additional logic (if you external component load any data from database) you can use Events, too.

Leave a Reply