First of all, you need to install typings for Google Analytics in your devDependencies
npm install --save-dev @types/google.analytics
Then add your tracking code in the base index.html
, and remove the last line as shown bellow:
<body>
<app-root>Loading...</app-root>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXXXX-ID', 'auto'); // <- add the UA-ID
// <- remove the last line
</script>
</body>
The next step consists to update your home component constructor for event tracking.
constructor(public router: Router) {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
ga('set', 'page', event.urlAfterRedirects);
ga('send', 'pageview');
}
});
}
If you want to track some specific event, you can also create a service and inject it into any component that you want to implement event tracking.
// ./src/app/services/google-analytics-events-service.ts
import {Injectable} from "@angular/core";
@Injectable()
export class GoogleAnalyticsEventsService {
public emitEvent(eventCategory: string,
eventAction: string,
eventLabel: string = null,
eventValue: number = null) {
ga('send', 'event', { eventCategory, eventLabel, eventAction, eventValue });
}
}
So if you want track a click on your home component for example, all you need to do is to inject the GoogleAnalyticsEventsService
and call the emitEvent()
method.
The updated home component source code:
constructor(public router: Router, public googleAnalyticsEventsService: GoogleAnalyticsEventsService) {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
ga('set', 'page', event.urlAfterRedirects);
ga('send', 'pageview');
}
});
}
submitEvent() { // event fired from home.component.html element (button, link, ... )
this.googleAnalyticsEventsService.emitEvent("testCategory", "testAction", "testLabel", 10);
}