### Component Setup for Launch Provider
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/launch/README.md
Import and inject Angulartics2LaunchByAdobe in your root component to start tracking route changes.
```typescript
import { Angulartics2LaunchByAdobe } from 'angulartics2';
@Component({ ... })
export class AppComponent {
// import Angulartics2LaunchByAdobe in root component
constructor(angulartics2LaunchByAdobe: Angulartics2LaunchByAdobe) {
angulartics2LaunchByAdobe.startTracking();
}
}
```
--------------------------------
### Initialize Angulartics2Module and Start Tracking
Source: https://context7.com/angulartics/angulartics2/llms.txt
Import `Angulartics2Module` into your root `NgModule` and configure it with `forRoot()`. Then, inject the analytics provider (e.g., `Angulartics2GoogleAnalytics`) into your root component to start tracking.
```typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { Angulartics2Module } from 'angulartics2';
import { Angulartics2GoogleAnalytics } from 'angulartics2';
const ROUTES: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
];
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(ROUTES),
// Register Angulartics2 with optional global settings
Angulartics2Module.forRoot(),
],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
export class AppModule {}
// Root component: inject provider and start tracking
import { Component } from '@angular/core';
import { Angulartics2GoogleAnalytics } from 'angulartics2';
@Component({ selector: 'app-root', template: '' })
export class AppComponent {
constructor(angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics) {
// Subscribes to pageTrack and eventTrack streams and forwards them to GA
angulartics2GoogleAnalytics.startTracking();
}
}
```
--------------------------------
### Install Angulartics2
Source: https://github.com/angulartics/angulartics2/blob/master/README.md
Install the angulartics2 package using npm.
```sh
npm install angulartics2 --save
```
--------------------------------
### NgModule Setup for Launch Provider
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/launch/README.md
Import Angulartics2LaunchByAdobe within your root NgModule's imports to enable Angulartics2 functionality.
```typescript
import { Angulartics2Module } from 'angulartics2';
import { Angulartics2LaunchByAdobe } from 'angulartics2';
@NgModule({
imports: [
...
// import Angulartics2LaunchByAdobe in root ngModule
Angulartics2Module.forRoot();
],
})
```
--------------------------------
### Clicky HTML Setup
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/clicky/README.md
Include this script in your index.html before the closing body tag. Replace XXXXX with your Clicky Site ID.
```html
```
--------------------------------
### Start Tracking with Angulartics2GoogleTagManager
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/gtm/README.md
Import Angulartics2GoogleTagManager in your root component and call startTracking() to enable route change tracking.
```typescript
import { Angulartics2GoogleTagManager } from 'angulartics2';
@Component({ ... })
export class AppComponent {
// import Angulartics2GoogleTagManager in root component
constructor(angulartics2GoogleTagManager: Angulartics2GoogleTagManager) {
angulartics2GoogleTagManager.startTracking();
}
}
```
--------------------------------
### Start Segment Tracking in Root Component
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/segment/README.md
Import `Angulartics2Segment` in your root component and inject it into the constructor to start tracking route changes.
```typescript
// component
import { Angulartics2Segment } from 'angulartics2';
@Component({ ... })
export class AppComponent {
constructor(angulartics2Segment: Angulartics2Segment) {
angulartics2Segment.startTracking();
}
}
```
--------------------------------
### Start Tracking Route Changes
Source: https://github.com/angulartics/angulartics2/blob/master/README.md
Import your analytics provider in the root component and call startTracking() to begin tracking route changes.
```ts
// component
import { Angulartics2GoogleAnalytics } from 'angulartics2';
@Component({ ... })
export class AppComponent {
constructor(angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics) {
angulartics2GoogleAnalytics.startTracking();
}
}
```
--------------------------------
### Start Tracking with Angulartics2GoogleGlobalSiteTag
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/gst/README.md
Inject Angulartics2GoogleGlobalSiteTag into your root component and call startTracking() to automatically send route changes to your analytics provider.
```typescript
import { Angulartics2GoogleGlobalSiteTag } from 'angulartics2';
@Component({ ... })
export class AppComponent {
// import Angulartics2GoogleGlobalSiteTag in root component
constructor(angulartics: Angulartics2GoogleGlobalSiteTag) {
angulartics.startTracking();
}
}
```
--------------------------------
### Angular Module Setup for Angulartics2
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/clicky/README.md
Configure your Angular module to use Angulartics2. Ensure Angulartics2Module.forRoot() is included in the imports.
```typescript
// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes, RouterOutlet } from '@angular/router';
import { AppComponent } from './app.component';
import { Angulartics2Module } from 'angulartics2';
import { PageComponent } from './page/page.component';
import { HomeComponent } from './home/home.component';
const ROUTES: Routes = [
{ path: '', component: HomeComponent},
{ path: 'page', component: PageComponent}
];
@NgModule({
declarations: [
AppComponent,
PageComponent,
HomeComponent
],
imports: [
BrowserModule,
RouterModule.forRoot(ROUTES),
Angulartics2Module.forRoot()
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
--------------------------------
### Splunk Tracking Code Setup
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/splunk/README.md
Add this JavaScript snippet to your HTML's
section. Ensure you replace the placeholder URL with your actual Splunk data collector address.
```javascript
var sp=sp||[];(function(){var e=["init","identify","track","trackLink","pageview"],t=function(e){return function(){sp.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var n=0;n
```
--------------------------------
### Start Incendium Tracking
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/incendium/README.md
Initialize Incendium tracking within your Angular component's constructor. Ensure the Angulartics2Incendium module is injected.
```typescript
constructor(Angulartics2Incendium: Angulartics2Incendium) {
Angulartics2Incendium.startTracking();
}
```
--------------------------------
### Track Matomo Ecommerce Events
Source: https://context7.com/angulartics/angulartics2/llms.txt
Use these methods to track ecommerce actions like viewing products, adding to cart, and completing purchases with Matomo. Ensure Matomo tracking is started with `matomo.startTracking()`.
```typescript
import { Component } from '@angular/core';
import { Angulartics2 } from 'angulartics2';
import { Angulartics2Matomo } from 'angulartics2';
@Component({ selector: 'app-shop', template: '' })
export class ShopComponent {
constructor(
private angulartics2: Angulartics2,
private matomo: Angulartics2Matomo,
) {
matomo.startTracking();
}
viewProduct(product: { sku: string; name: string; category: string; price: string }) {
// _paq.push(['setEcommerceView', sku, name, category, price])
this.angulartics2.eventTrack.next({
action: 'setEcommerceView',
properties: {
productSKU: product.sku,
productName: product.name,
categoryName: product.category,
price: product.price,
},
});
}
addToCart(item: { sku: string; name: string; category: string; price: string; qty: string }) {
// _paq.push(['addEcommerceItem', ...])
this.angulartics2.eventTrack.next({
action: 'addEcommerceItem',
properties: {
productSKU: item.sku,
productName: item.name,
productCategory: item.category,
price: item.price,
quantity: item.qty,
},
});
// _paq.push(['trackEcommerceCartUpdate', grandTotal])
this.angulartics2.eventTrack.next({
action: 'trackEcommerceCartUpdate',
properties: { grandTotal: '149.99' },
});
}
completePurchase() {
// _paq.push(['trackEcommerceOrder', orderId, grandTotal, subTotal, tax, shipping, discount])
this.angulartics2.eventTrack.next({
action: 'trackEcommerceOrder',
properties: {
orderId: 'ORD-5678',
grandTotal: '149.99',
subTotal: '129.99',
tax: '10.00',
shipping: '10.00',
discount: '0',
},
});
}
trackSearch(keyword: string, results: number) {
// _paq.push(['trackSiteSearch', keyword, category, searchCount])
this.angulartics2.eventTrack.next({
action: 'trackSiteSearch',
properties: { keyword, category: 'All', searchCount: String(results) },
});
}
setUserDimension(role: string) {
// Sets custom dimension1 via _paq.push(['setCustomDimension', 1, role])
this.angulartics2.setUserProperties.next({ dimension1: role });
}
}
```
--------------------------------
### Start Splunk Tracking in Component
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/splunk/README.md
Import and inject Angulartics2Splunk into your root component's constructor to begin tracking route changes.
```typescript
// component
import { Angulartics2Splunk } from 'angulartics2';
@Component({ ... })
export class AppComponent {
constructor(angulartics2Splunk: Angulartics2Splunk) {
angulartics2Splunk.startTracking();
}
}
```
--------------------------------
### Integrate Angulartics2 with Segment
Source: https://context7.com/angulartics/angulartics2/llms.txt
Use this snippet to integrate Angulartics2 with Segment. Ensure Segment provider is imported and started.
```typescript
import { Component } from '@angular/core';
import { Angulartics2 } from 'angulartics2';
import { Angulartics2Segment } from 'angulartics2';
@Component({ selector: 'app-root', template: '' })
export class AppComponent {
constructor(
private angulartics2: Angulartics2,
private segment: Angulartics2Segment,
) {
segment.startTracking();
}
onSignUp(user: { id: string; email: string; name: string }) {
// Calls analytics.identify(userId, traits)
this.angulartics2.setUserProperties.next({
userId: user.id,
email: user.email,
name: user.name,
});
}
onSubscribe() {
// Calls analytics.track('Subscribed', { plan: 'Pro' })
this.angulartics2.eventTrack.next({
action: 'Subscribed',
properties: { plan: 'Pro', trialDays: 14 },
});
}
onAnonymousLinked(newId: string) {
// Calls analytics.alias(newId)
this.angulartics2.setAlias.next(newId);
}
onLogout() {
// Calls analytics.reset() to clear identity
this.segment.unsetUserProperties();
}
}
```
--------------------------------
### Angulartics2 Routerless Setup
Source: https://context7.com/angulartics/angulartics2/llms.txt
Use `Angulartics2RouterlessModule` for applications not using `@angular/router`. This requires manual emission of page track events.
```typescript
import { NgModule, Component } from '@angular/core';
// --- Option A: No router ---
import { Angulartics2RouterlessModule } from 'angulartics2';
@NgModule({
imports: [
BrowserModule,
Angulartics2RouterlessModule.forRoot(),
],
})
export class AppModule {}
// --- Option B: UI-Router ---
import { Angulartics2UirouterModule } from 'angulartics2';
@NgModule({
imports: [
BrowserModule,
Angulartics2UirouterModule.forRoot(),
],
})
export class AppModule {}
// --- Manually emit page views when not using Angular Router ---
import { Angulartics2 } from 'angulartics2';
@Component({ selector: 'app-root', template: '' })
export class AppComponent {
constructor(private angulartics2: Angulartics2) {}
navigateTo(path: string) {
// Call after each virtual navigation
this.angulartics2.pageTrack.next({ path });
}
}
```
--------------------------------
### Track Event with Action and Category using Service
Source: https://github.com/angulartics/angulartics2/wiki/Tracking-Events
Use the `eventTrack.next()` method of the injected `Angulartics2` service to track events. This example tracks an event with a specified action and category.
```typescript
this.angulartics2.eventTrack.next({ action: 'myAction', properties: { category: 'myCategory' }});
```
--------------------------------
### Angulartics2 Module Setup
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/splunk/README.md
Configure Angulartics2 in your Angular application's root module. This enables the integration with analytics providers.
```typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { Angulartics2Module } from 'angulartics2';
const ROUTES: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent },
];
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(ROUTES),
// added to imports
Angulartics2Module.forRoot(),
],
declarations: [AppComponent],
bootstrap: [AppComponent],
})
```
--------------------------------
### Using Angulartics2 With UI-Router
Source: https://github.com/angulartics/angulartics2/blob/master/README.md
Integrate Angulartics2 with UI-Router in an Angular application. This support is experimental, and `@angular/router` must still be installed.
```typescript
import { Angulartics2UirouterModule } from 'angulartics2';
@NgModule({
// ...
imports: [
BrowserModule,
Angulartics2UirouterModule.forRoot(),
],
})
```
--------------------------------
### Dispatch Mixpanel Action from an Effect
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/mixpanel/README.md
Example of how to dispatch a Mixpanel track action from another NgRx effect, including custom properties.
```typescript
@Effect()
someEffect$ = this.actions$
.ofType(some.ACTION)
.map(action => new mixpanel.MixpanelTrack({
action: action.type,
properties: {
category: 'Your Category',
labelOrWhatever: 'LabelHere',
}
}));
```
--------------------------------
### Track Event with Label using Service
Source: https://github.com/angulartics/angulartics2/wiki/Tracking-Events
To include an event label when tracking events via the service, pass a `label` property within the `properties` object to the `eventTrack.next()` method. This example adds 'myLabel' to the event.
```typescript
this.angulartics2.eventTrack.next({ action: 'myAction', properties: { category: 'myCategory', label: 'myLabel' }});
```
--------------------------------
### Angulartics2Posthog Integration
Source: https://context7.com/angulartics/angulartics2/llms.txt
Integrates with PostHog's posthog-js SDK for page tracking, event capture, and user property management. Ensure posthog-js is installed and configured.
```typescript
import { Component } from '@angular/core';
import { Angulartics2 } from 'angulartics2';
import { Angulartics2Posthog } from 'angulartics2';
@Component({ selector: 'app-root', template: '' })
export class AppComponent {
constructor(
private angulartics2: Angulartics2,
private posthog: Angulartics2Posthog,
) {
posthog.startTracking();
// Or start page/event tracking separately:
// posthog.startPageTracking();
// posthog.startEventTracking();
}
onLogin(userId: string, email: string) {
// posthog.identify(userId)
this.angulartics2.setUsername.next(userId);
// posthog.identify(distinct_id, traits)
this.angulartics2.setUserProperties.next({ distinct_id: userId, email, plan: 'pro' });
// posthog.capture('Set User Properties Once', { $set_once: { ... } })
this.angulartics2.setUserPropertiesOnce.next({ signupDate: new Date().toISOString() });
}
setSuperProperties() {
// posthog.capture('Set Super Properties', { $set: { ... } })
this.angulartics2.setSuperProperties.next({ appVersion: '4.0.0' });
}
trackGroupEvent(companyId: string, companyName: string) {
// posthog.group('company', companyId, { name: companyName })
this.posthog.setGroup('company', companyId, { name: companyName });
}
trackFeatureFlag(flag: string) {
// posthog.capture('FeatureFlagViewed', { flag })
this.angulartics2.eventTrack.next({
action: 'FeatureFlagViewed',
properties: { flag, timestamp: Date.now() },
});
}
}
```
--------------------------------
### Integrate Angulartics2 with Mixpanel
Source: https://context7.com/angulartics/angulartics2/llms.txt
This snippet shows how to integrate Angulartics2 with Mixpanel. Start tracking and utilize Mixpanel's specific methods for user properties and events.
```typescript
import { Component } from '@angular/core';
import { Angulartics2 } from 'angulartics2';
import { Angulartics2Mixpanel } from 'angulartics2';
@Component({ selector: 'app-root', template: '' })
export class AppComponent {
constructor(
private angulartics2: Angulartics2,
private mixpanel: Angulartics2Mixpanel,
) {
mixpanel.startTracking();
}
onLogin(userId: string) {
// mixpanel.identify(userId)
this.angulartics2.setUsername.next(userId);
// mixpanel.people.set({ plan, createdAt })
this.angulartics2.setUserProperties.next({ plan: 'pro', createdAt: '2024-01-15' });
// mixpanel.people.set_once({ firstSeen })
this.angulartics2.setUserPropertiesOnce.next({ firstSeen: new Date().toISOString() });
}
setSuperProps() {
// mixpanel.register({ appVersion, env }) — sent with all future events
this.angulartics2.setSuperProperties.next({ appVersion: '3.1.0', env: 'prod' });
// mixpanel.register_once({ signupSource })
this.angulartics2.setSuperPropertiesOnce.next({ signupSource: 'organic' });
}
trackFeatureUsed(feature: string) {
// mixpanel.track('FeatureUsed', { feature, timestamp })
this.angulartics2.eventTrack.next({
action: 'FeatureUsed',
properties: { feature, timestamp: Date.now() },
});
}
}
```
--------------------------------
### Track Events with Label using Directive
Source: https://github.com/angulartics/angulartics2/wiki/Tracking-Events
To include an event label when using directives, add the `angularticsProperties` attribute and bind it to an object containing the `label` property. This example adds a 'Fall Campaign' label to the DownloadClick event.
```html
```
--------------------------------
### Boot and Track Events with Angulartics2Intercom
Source: https://context7.com/angulartics/angulartics2/llms.txt
Initialize Intercom with user properties and forward page views and custom events. This snippet shows how to boot Intercom and track specific user actions.
```typescript
import {
Component
} from '@angular/core';
import {
Angulartics2
} from 'angulartics2';
import {
Angulartics2Intercom
} from 'angulartics2';
@Component({
selector: 'app-root',
template: ''
})
export class AppComponent {
constructor(
private angulartics2: Angulartics2,
private intercom: Angulartics2Intercom,
) {
intercom.startTracking();
}
bootIntercom(user: { id: string; email: string; name: string; createdAt: number }) {
// Intercom('boot', { user_id, email, name, created_at })
this.angulartics2.setUserProperties.next({
userId: user.id, // auto-mapped to user_id for Intercom
email: user.email,
name: user.name,
created_at: user.createdAt,
});
}
trackEvent(action: string, metadata: object) {
// Intercom('trackEvent', action, metadata)
this.angulartics2.eventTrack.next({ action, properties: metadata });
}
}
```
--------------------------------
### Root Component Initialization
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/matomo/README.md
Inject Angulartics2Matomo into your root component and call startTracking() to initialize it.
```typescript
import { Angulartics2Matomo } from 'angulartics2';
export class AppComponent {
// inject Angulartics2Matomo in root component and initialize it
constructor(private angulartics2Matomo: Angulartics2Matomo) {
angulartics2Matomo.startTracking();
}
}
```
--------------------------------
### Add IBM Digital Analytics Script to index.html
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/ibm-digital-analytics/README.md
Include this script in your index.html file before the closing body tag. Replace XXXXXXXXX with your Client ID and other necessary parameters for cmSetClientID.
```html
```
--------------------------------
### SystemJS Configuration for Angulartics2
Source: https://github.com/angulartics/angulartics2/blob/master/README.md
Configure SystemJS to correctly load Angulartics2 if `defaultJSExtensions` is not set to `true`.
```javascript
System.config({
packages: {
"/angulartics2": {"defaultExtension": "js"},
},
});
```
--------------------------------
### Bootstrap Angulartics2Module for GTM
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/gtm/README.md
Import Angulartics2Module.forRoot() in your root ngModule to initialize Angulartics2 with the Google Tag Manager provider.
```typescript
import { Angulartics2Module } from 'angulartics2';
@NgModule({
imports: [
...
// import Angulartics2GoogleTagManager in root ngModule
Angulartics2Module.forRoot()
],
})
```
--------------------------------
### Handle Offline Tracking with Response Subscription
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/incendium/README.md
Implement offline tracking by subscribing to `incendiumResponse`. This allows you to process the response from Incendium, including keys for later use, and handle errors gracefully. Remember to unsubscribe to prevent memory leaks.
```typescript
export class Example implements OnInit {
private incSubscription;
constructor(
private angulartics2: Angulartics2,
private angulartics2Incendium: Angulartics2Incendium,
) {}
ngOnInit(): void {
this.incSubscription = this.angulartics2Incendium.incendiumResponse.subscribe({
next: v => {
if (v.type === IncendiumEventNames.ADD_CONVERION) {
this.submit(v.value);
}
},
error: e => {
console.error(e);
// submit without key or handle how you like
this.submit();
},
});
}
ngOnDestroy(): void {
// Dont forget to unsubscribe
this.incSubscription.unsubscribe();
}
onSubmit() {
this.angulartics2.eventTrack.next({
action: IncendiumEventNames.ADD_CONVERION,
properties: {
key: 'my_trigger_as_assigned_in_incendium',
},
});
}
submit(incendiumKey?: string) {
alert(`form submitted with ${incendiumKey ? `key ${incendiumKey}` : `no key`}`);
}
}
```
--------------------------------
### Angular Module Configuration
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/matomo/README.md
Import Angulartics2Module and Angulartics2Matomo into your app.module.
```typescript
import { Angulartics2Module } from 'angulartics2';
import { Angulartics2Matomo } from 'angulartics2';
@NgModule({
imports: [
Angulartics2Module.forRoot(),
...
```
--------------------------------
### Configure Angulartics2Module with Global Settings
Source: https://context7.com/angulartics/angulartics2/llms.txt
Configure the root module with global page-tracking options using `Angulartics2Module.forRoot()`. This method accepts a `Partial` object for customization.
```typescript
import { Angulartics2Module } from 'angulartics2';
@NgModule({
imports: [
Angulartics2Module.forRoot({
// Disable tracking for all routes during development
developerMode: false,
pageTracking: {
// Automatic virtual pageview tracking on NavigationEnd (default: true)
autoTrackVirtualPages: true,
// Prepend a base path to all tracked URLs
basePath: '',
// Exclude specific routes from tracking (string or RegExp)
excludedRoutes: [
'/admin',
/
/[0-9]{4}
/
/[0-9]{2}
/
/[a-zA-Z0-9|\-]*
],
// Strip numeric and UUID segments from URLs: /project/12981/feature → /project/feature
clearIds: true,
// Custom regex for ID removal: /project/a01/feature → /project/feature
idsRegExp: new RegExp('^[a-z]\d+$'),
// Strip query strings: /page?param=123 → /page
clearQueryParams: true,
// Strip hash fragments: /callback#authcode=123 → /callback
clearHash: true,
},
// Provider-specific settings
ga: {
additionalAccountNames: ['secondTracker'],
userId: null,
transport: 'beacon',
anonymizeIp: true,
},
gst: {
trackingIds: ['G-XXXXXXXXXX'],
anonymizeIp: false,
customMap: { dimension1: 'user_type' },
},
gtm: {
userId: null,
},
}),
],
})
export class AppModule {}
```
--------------------------------
### Using Angulartics2 Without a Router
Source: https://github.com/angulartics/angulartics2/blob/master/README.md
Integrate Angulartics2 in an Angular application without using `@angular/router`. Ensure `@angular/router` is installed, though it won't be actively used.
```typescript
import { Angulartics2RouterlessModule } from 'angulartics2';
@NgModule({
// ...
imports: [
BrowserModule,
Angulartics2RouterlessModule.forRoot(),
],
})
```
--------------------------------
### Track Events with Directive Attributes
Source: https://github.com/angulartics/angulartics2/wiki/Tracking-Events
Use the `angulartics2On`, `angularticsEvent`, and `angularticsCategory` attributes on an HTML element to track events when that element is interacted with. This example shows tracking a click event.
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'song-download-box',
template: ``,
})
export class SongDownloadBox {}
```
```typescript
import { NgModule } from '@angular/core';
import { Angulartics2Module } from 'angulartics2';
@NgModule({
imports: [
Angulartics2Module.forChild()
],
declarations: [ SongDownloadBox ]
})
```
--------------------------------
### Bootstrap Angulartics2 with Google Global Site Tag
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/gst/README.md
Import Angulartics2Module in your root NgModule to enable Google Global Site Tag tracking. This sets up the necessary providers for Angulartics2.
```typescript
import {
Angulartics2Module
} from 'angulartics2';
@NgModule({
imports: [
...
// import Angulartics2GoogleGlobalSiteTag in root ngModule
Angulartics2Module.forRoot()
],
})
export class AppModule { }
```
--------------------------------
### Bootstrap Angulartics2 with Google Analytics Provider
Source: https://github.com/angulartics/angulartics2/wiki/Google-Analytics
Integrate Angulartics2 and the Google Analytics provider into your Angular application's root module and component. This setup automatically tracks route changes.
```typescript
// component
import { Angulartics2GoogleAnalytics } from 'angulartics2';
import { Component } from '@angular/core';
@Component({
selector: 'app',
template: '' // Or what your root template is.
})
export class AppComponent {
constructor(angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics) {}
}
```
```typescript
// 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 ]
})
```
--------------------------------
### Enable Auto Route Logging with IBM Digital Analytics
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/ibm-digital-analytics/README.md
In your AppComponent, inject the Angulartics2IBMDigitalAnalytics service and call startTracking() in the constructor to automatically log route changes.
```typescript
// app.component.ts
import { Component } from '@angular/core';
import { Angulartics2IBMDigitalAnalytics } from 'angulartics2';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// Enable route logging
constructor(angulartics2IBMDigitalAnalytics: Angulartics2IBMDigitalAnalytics) {
angulartics2IBMDigitalAnalytics.startTracking();
}
}
```
--------------------------------
### Enable Auto Route Logging with Clicky
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/clicky/README.md
In your root component, inject Angulartics2Clicky and call startTracking() to enable automatic logging of route changes.
```typescript
// app.component.ts
import { Component } from '@angular/core';
import { Angulartics2Clicky } from 'angulartics2-clicky';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
// Enable auto route logging
constructor(angulartics2Clicky: Angulartics2Clicky) {
angulartics2Clicky.startTracking();
}
}
```
--------------------------------
### Track Events with Angulartics2Amplitude
Source: https://context7.com/angulartics/angulartics2/llms.txt
Use this snippet to track custom events and user properties with Amplitude. Ensure Amplitude's JS SDK is initialized. Pageviews are tracked automatically on navigation.
```typescript
import {
Component
} from '@angular/core';
import {
Angulartics2
} from 'angulartics2';
import {
Angulartics2Amplitude
} from 'angulartics2';
@Component({
selector: 'app-root',
template: ''
})
export class AppComponent {
constructor(
private angulartics2: Angulartics2,
private amplitude: Angulartics2Amplitude,
) {
amplitude.startTracking();
// amplitude.getInstance().logEvent('Pageview', { url }) called on NavigationEnd
}
onLogin(userId: string) {
// amplitude.getInstance().setUserId(userId)
this.angulartics2.setUsername.next(userId);
// amplitude.getInstance().setUserProperties({ plan, role })
this.angulartics2.setUserProperties.next({ plan: 'enterprise', role: 'admin' });
}
trackButtonClick(buttonName: string) {
// amplitude.getInstance().logEvent('ButtonClicked', { name })
this.angulartics2.eventTrack.next({
action: 'ButtonClicked',
properties: { name: buttonName, screen: 'Dashboard' },
});
}
}
```
--------------------------------
### Tracking Custom Variables
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/matomo/README.md
Use setUserProperties to track custom variables. Call this method multiple times to track several variables.
```typescript
angulartics2.setUserProperties.next({index: 1, name: 'John', value: 123, scope: 'visit'});
```
--------------------------------
### Configure Custom Map and Tracking IDs
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/gst/README.md
Configure custom dimensions, tracking IDs, and other settings like anonymizeIp during the Angulartics2Module.forRoot() call. This approach is recommended over setting config in HTML.
```typescript
import {
Angulartics2Module
} from 'angulartics2';
@NgModule({
imports: [
...
// import Angulartics2GoogleGlobalSiteTag in root ngModule
Angulartics2Module.forRoot(
gst: {
trackingIds: ['UA-11111111-1'],
customMap: {
dimension1: 'version',
dimension2: 'page_language',
dimension3: 'custom_dimension_name'
},
anonymizeIp: true
},
)
],
})
export class AppModule { }
```
--------------------------------
### Track Events and Goals with Clicky Directives
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/clicky/README.md
Use the angulartics2On and angularticsAction directives to track button clicks as events or goals. Properties like 'goal', 'revenue', and 'noQueue' can be specified.
```html
```
--------------------------------
### Track Events with Angulartics2Facebook
Source: https://context7.com/angulartics/angulartics2/llms.txt
Send standard and custom events to Facebook Pixel. Standard events use `fbq('track', ...)` and custom events use `fbq('trackCustom', ...)`. Page tracking is not included by default.
```typescript
import {
Component
} from '@angular/core';
import {
Angulartics2
} from 'angulartics2';
import {
Angulartics2Facebook
} from 'angulartics2';
// Standard Facebook Pixel event names:
// 'ViewContent' | 'Search' | 'AddToCart' |
// 'AddToWishlist' |
// 'InitiateCheckout' | 'AddPaymentInfo' | 'Purchase' | 'Lead' |
// 'CompleteRegistration'
@Component({
selector: 'app-root',
template: ''
})
export class AppComponent {
constructor(
private angulartics2: Angulartics2,
private fb: Angulartics2Facebook,
) {
fb.startTracking(); // Page tracking is NOT included for Facebook Pixel
}
onProductView(product: { id: string; name: string; price: number }) {
// fbq('track', 'ViewContent', { content_ids, content_name, value, currency })
this.angulartics2.eventTrack.next({
action: 'ViewContent',
properties: {
content_ids: [product.id],
content_name: product.name,
value: product.price,
currency: 'USD',
},
});
}
onPurchase(orderId: string, value: number) {
// fbq('track', 'Purchase', { ... })
this.angulartics2.eventTrack.next({
action: 'Purchase',
properties: { value, currency: 'USD', order_id: orderId },
});
}
onCustomAction(action: string, data: object) {
// fbq('trackCustom', action, data) — for non-standard event names
this.angulartics2.eventTrack.next({ action, properties: data });
}
}
```
--------------------------------
### Bootstrap Angulartics2 with Google Tag Manager
Source: https://github.com/angulartics/angulartics2/wiki/Google-Tag-Manager
Import and inject Angulartics2 and the Google Tag Manager provider into your root component and NgModulesto enable tracking. This hooks into the router to send route changes.
```typescript
import { Angulartics2GoogleTagManager } from 'angulartics2';
import { Component } from '@angular/core';
@Component({
selector: 'app',
template: ''
})
export class AppComponent {
constructor(angulartics2GoogleTagManager: Angulartics2GoogleTagManager) {}
}
```
```typescript
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouterModule, Routes } from '@angular/router';
import { Angulartics2Module, Angulartics2GoogleTagManager } from 'angulartics2';
const ROUTES: Routes = [
{ path: '', component: HomeComponent },
{ path: 'about', component: AboutComponent }
];
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(ROUTES),
Angulartics2Module.forRoot([ Angulartics2GoogleTagManager ])
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
```
--------------------------------
### Tracking Custom Dimensions
Source: https://github.com/angulartics/angulartics2/blob/master/src/lib/providers/matomo/README.md
Use setUserProperties to track custom dimensions. Custom Variables and Custom Dimensions require separate calls to setUserProperties.
```typescript
angulartics2.setUserProperties.next({
dimension1: 'v1.2.3',
dimension2: 'german',
dimension43: 'green',
});
```
--------------------------------
### Angulartics2GoogleAnalytics: Track Events and User Data
Source: https://context7.com/angulartics/angulartics2/llms.txt
Use this provider to forward page views, events, exceptions, and user data to Universal Analytics (analytics.js). Ensure `ga.startTracking()` is called in the constructor.
```typescript
import { Component } from '@angular/core';
import { Angulartics2 } from 'angulartics2';
import { Angulartics2GoogleAnalytics } from 'angulartics2';
@Component({ selector: 'app-root', template: '' })
export class AppComponent {
constructor(
private angulartics2: Angulartics2,
private ga: Angulartics2GoogleAnalytics,
) {
ga.startTracking(); // Subscribes GA to all pageTrack/eventTrack/etc. subjects
}
trackPurchase() {
// Standard event with category, label, value
this.angulartics2.eventTrack.next({
action: 'Purchase',
properties: {
category: 'Ecommerce',
label: 'Pro Plan',
value: 99,
noninteraction: false,
// Custom dimensions and metrics
dimension1: 'premium-user',
metric1: 1,
},
});
}
trackTiming(ms: number) {
this.angulartics2.userTimings.next({
timingCategory: 'API',
timingVar: 'response',
timingValue: ms,
timingLabel: '/api/users',
});
}
trackError(err: Error) {
this.angulartics2.exceptionTrack.next({
description: err.message,
fatal: false,
});
}
identifyUser(userId: string) {
// Sets userId on all GA trackers including additionalAccountNames
this.angulartics2.setUsername.next(userId);
}
}
```
--------------------------------
### Track Events with Label and Properties in Code
Source: https://github.com/angulartics/angulartics2/blob/master/README.md
Track events from code, including event labels and custom properties, by structuring the payload passed to the eventTrack observable.
```ts
this.angulartics2.eventTrack.next({
action: 'myAction',
properties: {
category: 'myCategory',
label: 'myLabel',
},
});
```
--------------------------------
### Track Events with Label and Value in Templates
Source: https://github.com/angulartics/angulartics2/blob/master/README.md
Extend the angulartics2On directive to include event labels, values, and custom properties for more detailed event tracking.
```html
Click Me
```
--------------------------------
### Angulartics2GoogleGlobalSiteTag: Configure and Track with gtag.js
Source: https://context7.com/angulartics/angulartics2/llms.txt
This provider uses `gtag()` for GA4 and Universal Analytics. Configure tracking IDs, anonymize IP, and map custom dimensions in the `Angulartics2Module.forRoot` configuration. Ensure `gst.startTracking()` is called in the component's constructor.
```typescript
import { NgModule, Component } from '@angular/core';
import { Angulartics2Module } from 'angulartics2';
import { Angulartics2 } from 'angulartics2';
import { Angulartics2GoogleGlobalSiteTag } from 'angulartics2';
@NgModule({
imports: [
Angulartics2Module.forRoot({
gst: {
trackingIds: ['G-XXXXXXXXXX', 'UA-XXXXXXX-X'],
anonymizeIp: true,
customMap: { dimension1: 'user_role' },
},
}),
],
})
export class AppModule {}
@Component({ selector: 'app-root', template: '' })
export class AppComponent {
constructor(
private angulartics2: Angulartics2,
private gst: Angulartics2GoogleGlobalSiteTag,
) {
gst.startTracking();
}
trackVideoPlay(videoId: string, duration: number) {
this.angulartics2.eventTrack.next({
action: 'video_play',
properties: {
category: 'Video',
label: videoId,
value: Math.round(duration),
// GST-specific custom parameters
gstCustom: { video_provider: 'youtube', video_duration: duration },
},
});
}
setUserDimension(role: string) {
// Sets dimension1 → user_role on all subsequent gtag calls
this.angulartics2.setUserProperties.next({ dimension1: role });
}
}
```
--------------------------------
### Angulartics2HubSpot Integration
Source: https://context7.com/angulartics/angulartics2/llms.txt
Pushes page views and events to HubSpot via `_hsq`. Supports contact identification. Ensure HubSpot tracking code is correctly implemented.
```typescript
import { Component } from '@angular/core';
import { Angulartics2 } from 'angulartics2';
import { Angulartics2Hubspot } from 'angulartics2';
@Component({ selector: 'app-root', template: '' })
export class AppComponent {
constructor(
private angulartics2: Angulartics2,
private hubspot: Angulartics2Hubspot,
) {
hubspot.startTracking();
}
identifyContact(email: string, firstName: string) {
// _hsq.push(['identify', { email, firstname }])
this.angulartics2.setUserProperties.next({ email, firstname: firstName });
}
trackFormConversion() {
// _hsq.push(['trackEvent', properties])
this.angulartics2.eventTrack.next({
action: 'FormSubmit',
properties: { id: 'contact-us-form', value: 1 },
});
}
}
```