Search code examples
angulargoogle-analyticsangular-routerangular12

Angular (v12) detect browser triggered navigation to send Google analytics call


Having 'ga' call in app.component.ts in router event works only when we navigate from the app, if you enter a path in the browser search bar directly the event is not triggered.

app.component.ts

ngAfterViewInit() {
    this.router.events.subscribe((event: any) => {
      if(event instanceof NavigationEnd) {
        ga('set', 'page', event.urlAfterRedirects);
        ga('send', 'pageview');
      }
    })
  }

Navigating directly to a path from browser like https://example.com/some-path does not trigger the above event.

Having 'ga' call in ngOnInit() in every route is a solution but its redundant. Any effective solution for this?

And also having the above ga code in ngOnInit() instead of ngAfterViewInit() also does not help.


Solution

  • Just in case if someone is having the same problem, like the question says in local when you do ng s GA does not work on browser triggered navigation, but in the production server, since we configure nginx/apache to serve angular app we redirect 404 pages to root of the app and from there angular handles redirections to specified route or a 404 page, this is treated as in app navigation and GA works.

    nginx config:

    try_files $uri $uri/ /index.html;