Add Privatus Analytics to Angular
Add privacy-friendly analytics to an Angular app in src/index.html, handle hash location routing and track custom events from an injectable Angular service.
Add the snippet to src/index.html inside <head>:
html
<script defer src="https://privatusanalytics.com/js/pa.js" data-site="pa_YOURSITEID"></script>
The Angular router uses history.pushState by default, which the tracker
follows. With withHashLocation() (or useHash: true), add
data-spa="hash".
Events#
Declare the global once and call it from a service:
ts
// privatus.service.ts
import { Injectable } from '@angular/core'
declare global {
interface Window { privatus?: { track(name: string, props?: Record<string, unknown>): void } }
}
@Injectable({ providedIn: 'root' })
export class PrivatusService {
track(name: string, props: Record<string, string | number | boolean> = {}) {
window.privatus?.track(name, props)
}
}
With server-side rendering (Angular Universal / SSR), the snippet in
index.html still only runs in the browser, and the service's optional
call is a no-op on the server.