Skip to content

Google Analytics

Scott Cooper edited this page Mar 11, 2018 · 8 revisions

The wiki is deprecated. Please see the project home or the provider folder for documentation


Minimal setup for Google Analytics

Add the full tracking code from Google Tag Manager to the beginning of your body tag.

Changes in the Google Analytics snippet

The snippet code provided by Google Analytics does an automatic pageview hit, but this is already done by Angulartics (unless you disable it) so make sure to delete the tracking line:

      ...
      ga('create', 'UA-XXXXXXXX-X', 'none'); // 'none' while you are working on localhost
      ga('send', 'pageview');  // DELETE THIS LINE!
    </script>

Include it in your application

Bootstrapping the application with Angulartics2 as provider and injecting both Angulartics2 and Angulartics2GoogleAnalytics (or any provider) into the root component will hook into the router and send every route change to your analytics provider.

// component
import { Angulartics2GoogleAnalytics } from 'angulartics2';
import { Component } from '@angular/core';

@Component({
  selector: 'app',
  template: `<router-outlet></router-outlet>` // Or what your root template is.
})
export class AppComponent {
  constructor(angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics) {}
}

// bootstrap
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { Angulartics2Module, Angulartics2GoogleAnalytics } from 'angulartics2';

const ROUTES: Routes = [
  { path: '',      component: HomeComponent },
  { path: 'about', component: AboutComponent }
];

@NgModule({
  imports: [
    BrowserModule,
    RouterModule.forRoot(ROUTES),

    Angulartics2Module.forRoot([ Angulartics2GoogleAnalytics ])
  ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ]
})

For detailed instructions on how to send tracking events in a component or in a template check out the documentation for Tracking Events.