Provider: Google Analytics (analytics.js)
Setup
To use the Google Analytics provider with analytics.js, follow these steps.
Note: If Google suggests you use
gtag.js, you should use the Google Global Site Tag provider instead.
1. Add Google Analytics Snippet
Add the analytics.js tracking code provided by Google to your index.html. Place it in the <head> or at the beginning of your <body> tag.
Important: You must remove the ga('send', 'pageview'); line from the standard snippet to prevent duplicate pageviews, as Angulartics2 will handle this for you.
<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-XXXXXXXX-X', 'auto'); // Use 'none' for localhost development
// ga('send', 'pageview'); <-- DELETE THIS LINE!
</script>
2. Configure Angulartics2
In your root component (e.g., app.component.ts), inject the Angulartics2GoogleAnalytics service and call startTracking().
import { Component } from '@angular/core';
import { Angulartics2GoogleAnalytics } from 'angulartics2';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
})
export class AppComponent {
constructor(angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics) {
angulartics2GoogleAnalytics.startTracking();
}
}
This will activate automatic page tracking and enable event tracking for Google Analytics.