I have built a new site using Angular 2 as the front-end. As everything is done via push state, there are no page loads which typically trigger the Google Analytics code to
Assuming that every Angular Route has its own title in app.routing.ts:
{
path: 'shop',
component: ShopComponent,
data: {
title: ' == This is Shop Component Title =='
},
canActivate: [AuthGuard]
},
Previously mentioned solutions will still display the same page title for each route on Google Analytics Report. In order to make use of corresponding Angular Route titles ( instead of index.html tag content all the time), use the code below in app.component.ts
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
(window).ga('set', 'page', event.urlAfterRedirects);
// ----------
//use the following 3 lines of code to use
//correnct titles for routes
// ----------
let currentRoute = this.route.root;
let title = this.getPageTitle(currentRoute);
(window).ga('set', 'title', title);
(window).ga('send', 'pageview');
}
});
...where getPageTitle method is as follows:
getPageTitle = function (currentRoute: ActivatedRoute) {
let data;
do {
const childrenRoutes = currentRoute.children;
currentRoute = null;
childrenRoutes.forEach(route => {
if (route.outlet === 'primary') {
currentRoute = route;
data = route.snapshot.data;
}
});
} while (currentRoute);
return data.title;
};
Note: This solution applies to Anguler 5 and below. In Angular 6, you can also use TitleService