How to implement google analytics in angular?

by alvera_smith , in category: SEO Tools , 6 months ago

How to implement google analytics in angular?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by drew , 6 months ago

@alvera_smith 

To implement Google Analytics in an Angular application, you can follow these steps:

  1. Sign up for a Google Analytics account and create a new property for your Angular application.
  2. Install the angular-ga library by running the following command in your project directory:
1
npm install angular-ga


  1. In your Angular app's module file (app.module.ts), import the AngularGoogleAnalyticsModule and add it to the imports array:
1
2
3
4
5
6
7
8
9
import { AngularGoogleAnalyticsModule, GaService } from 'angular-ga';

@NgModule({
  imports: [
    AngularGoogleAnalyticsModule
  ],
  providers: [GaService]
})
export class AppModule { }


  1. In your Angular app's component file where you want to track the page views, import the GaService:
1
import { GaService } from 'angular-ga';


  1. Inject the GaService in the constructor of the component:
1
constructor(private gaService: GaService) { }


  1. Call the register method of the GaService in the component's ngOnInit() method to initialize tracking with your Google Analytics tracking ID:
1
2
3
ngOnInit() {
  this.gaService.register('GA_TRACKING_ID');
}


  1. To track page views, call the trackPage() method of the GaService whenever the route changes in your Angular app:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import { Router, NavigationEnd } from '@angular/router';

constructor(private gaService: GaService, private router: Router) { }

ngOnInit() {
  this.gaService.register('GA_TRACKING_ID');

  this.router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
      this.gaService.trackPage(event.urlAfterRedirects);
    }
  });
}


  1. Finally, rebuild and run your Angular application. The Google Analytics tracking code will be injected into your application and page views will be recorded.


Note that 'GA_TRACKING_ID' in the code snippets should be replaced with your own Google Analytics tracking ID.


Remember to comply with Google Analytics terms of service and privacy policies when implementing tracking in your application.