Until now, I was using Google Analytics directly and I was firing Page View Event manually with JavaScript from app.component.ts
, like this:
declare var gtag: Function;
...
constructor(private router: Router) {
const navEndEvents = this.router.events.pipe(
filter((event) => event instanceof NavigationEnd)
);
navEndEvents.subscribe((event: NavigationEnd) => {
gtag('config', 'xxx', {
page_path: event.urlAfterRedirects,
page_title: event.urlAfterRedirects
});
})
}
Now, I want to use Google Analytics through Google Tag Manager, and not directly. How should I send Page View Event now?
I was able to do it with angular-google-tag-manager package. Once you install and configure package, you can send whatever event to GTM really easy. Refactor for Page View Event in app.component.ts
looks like this:
import { GoogleTagManagerService } from 'angular-google-tag-manager';
constructor(private router: Router, private gtmService: GoogleTagManagerService) {
const navEndEvents = this.router.events.pipe(
filter((event) => event instanceof NavigationEnd)
);
navEndEvents.subscribe((event: NavigationEnd) => {
this.gtmService.pushTag({ event: 'page', pageName: event.urlAfterRedirects });
});
}