Skip to content
Advertisement

Angular – Google analytics not tracking page path changes

I have set up google analytics GA4 and added the snippets to my Angular application:

index.html:

  <script async src="https://www.googletagmanager.com/gtag/js?id=G-mytagid"></script>

  <script>
    window.dataLayer = window.dataLayer || [];

    function gtag() {
      dataLayer.push(arguments);
    }

    gtag('js', new Date());
  </script>

then in app.component.ts:

this.router.events.subscribe(event => {
  if (event instanceof NavigationEnd) {
    console.log(event.urlAfterRedirects);
    gtag('config', 'G-mytagid',
      {
        'page_path': event.urlAfterRedirects,
      }
    );
  }
});

Google analytics dashboard detects the page views and changes and also the console also logs the urlAfterRedirects, but on the GA dashboard my application name increments without change in the actual path. I am wanting to tack the actual path/ page we are on.

I am wondering how to do this?

Thanks

Advertisement

Answer

You should execute gtag('config', ...); only once per page, so you should better put it your index.html. This “loads” your GA4 and automatically starts collecting some events (see below).

There is no “default” event parameter page_path in GA4, your code collects data in a custom dimensions which you need to map before you can see it.

Anyway: First you might want to check for your Enhanced measurement settings: [GA4] Enhanced event measurement

There you might want to disable “Page changes based on browser history events” under “Show advanced settings” of “Page views”.

You cannot disable the page_view GA4 is sending as soon as it loads there, but you can do it in your gtag('config', ...);:

gtag('config', 'G-...', {
    'send_page_view': false
});

In your NavigationEnd event handler, you want to send a page_view event:

gtag('event', 'page_view', {
  'page_location': document.location.origin + event.urlAfterRedirects,
  'page_title': document.title
});
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement