I have an Angular website which I would like to use Google Analytics with to track the page views. Im using Firebase through @angular/fire
to host my website. Therefore, I added the @angular/fire
library by ng add @angular/fire
and enabled the services I needed, plus analytics.
Now according to the docs I can see how one can inject AngularFireAnalytics
in their component to log page views:
import { AngularFireAnalytics } from '@angular/fire/compat/analytics';
constructor(analytics: AngularFireAnalytics) {
analytics.logEvent('custom_event', { ... });
}
But Im not able to find a way to only enable the whole analytics only on a specific route, and no where else in the website.
I want to set up different paths for the same LandingPageComponent
, so that I can visualize the page views from different advertisement funnels. In general I do not want any means of analytics on any other part of the website except for the page view events related to these URLs that end up in the same component after all.
I managed to solve my question by defining a custom event and adding a condition to check for the specific route that I wanted in the component by injecting Location
service from Angular:
import {Component, OnInit} from '@angular/core';
import {Location} from "@angular/common";
import {AngularFireAnalytics} from "@angular/fire/compat/analytics";
@Component({
selector: 'app-xxx',
templateUrl: './xxx.component.html',
styleUrls: ['./xxx.component.scss'],
})
export class XxxComponent implements OnInit {
constructor(readonly location: Location,
readonly analytics: AngularFireAnalytics) { }
ngOnInit(): void {
if (this.location.path() === '/myPath') {
this.analytics.logEvent('custom_event', { ... });
}
}
}
According to what I read, it is not possible to disable the default analytics data collection and instead to just send your custom event. Therefore, you either have to have default data collection enabled and send your custom event, or completely turn analytics off. Although, you can turn on and off the analytics from the component, which I'm not sure if its a good practice.
Please let me know if there is an alternative and better solution.