Installation Guide
Follow these steps to install and configure Angulartics2 in your Angular project.
Prerequisites
Ensure your project is using a compatible version of Angular. Based on the project's dependencies, Angulartics2 is compatible with Angular 15.x.
| Angulartics2 | Angular |
|---|---|
| 8.3.0 | 8.x |
| 9.1.0 | 9.x |
| 10.1.0 | 10.x |
| 11.0.0 | 12.x |
| 12.0.0 | 13.x |
| 13.0.0 | 14.x |
| latest | 15.x |
Step 1: Install the Package
Install Angulartics2 into your project using npm or yarn.
npm install angulartics2 --save
Or with yarn:
yarn add angulartics2
Step 2: Import Angulartics2Module
In your root application module (usually app.module.ts), import Angulartics2Module and add it to your imports array.
The .forRoot() method initializes the core Angulartics2 service.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
// Import Angulartics2
import { Angulartics2Module } from 'angulartics2';
// Your components
import { AppComponent } from './app.component';
import { HomeComponent } from './home.component';
const ROUTES: Routes = [
{ path: '', component: HomeComponent },
];
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(ROUTES),
// Add Angulartics2Module.forRoot() to your imports
Angulartics2Module.forRoot(),
],
declarations: [AppComponent, HomeComponent],
bootstrap: [AppComponent],
})
export class AppModule { }
Step 3: Configure a Provider
Angulartics2 requires at least one analytics provider to send data to. You must inject the chosen provider's service into your root component (e.g., AppComponent) and call startTracking() to enable automatic page view tracking.
Here is an example using Google Analytics:
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();
}
}
Important:
- Replace
Angulartics2GoogleAnalyticswith the service for your chosen provider (e.g.,Angulartics2Mixpanel,Angulartics2Segment). - The call to
startTracking()is required to begin listening to router events for automatic page view tracking. - You will also need to add the provider's own script to your
index.html. See the documentation for your specific provider for more details. You can find provider-specific guides in the Providers section.
With these steps completed, Angulartics2 is now installed and configured to automatically track page views in your application.