@alvera_smith
To implement Google Analytics in an Angular application, you can follow these steps:
- Sign up for a Google Analytics account and create a new property for your Angular application.
- Install the angular-ga library by running the following command in your project directory:
- 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 { }
|
- In your Angular app's component file where you want to track the page views, import the GaService:
1
|
import { GaService } from 'angular-ga';
|
- Inject the GaService in the constructor of the component:
1
|
constructor(private gaService: GaService) { }
|
- 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');
}
|
- 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);
}
});
}
|
- 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.