Skip to content

Instantly share code, notes, and snippets.

@Walgermo
Last active January 22, 2021 20:33
Show Gist options
  • Save Walgermo/9088d1ec1b652bc634b354a9ea7a23c7 to your computer and use it in GitHub Desktop.
Save Walgermo/9088d1ec1b652bc634b354a9ea7a23c7 to your computer and use it in GitHub Desktop.
Angular 6 - Globally set meta title in app on route change
import { Injectable } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';
import { filter, map, mergeMap } from 'rxjs/operators';
/**
* Call updateTitle() from app.component.ts contructor.
* Example app.component.ts:
constructor(private meta: MetaService) {
this.meta.updateTitle();
}
* Optional override title with passing a title parameter.
* Format routes as follow:
{
path: 'about',
component: AboutComponent,
data: {
title: 'About',
description:'Description Meta Tag Content'
}
},
**/
@Injectable({
providedIn: 'root'
})
export class MetaService {
constructor(
private titleService: Title,
private router: Router,
private activatedRoute: ActivatedRoute
) { }
updateTitle(title?: string) {
if (!title) {
this.router.events
.pipe(
filter((event) => event instanceof NavigationEnd),
map(() => this.activatedRoute),
map((route) => {
while (route.firstChild) { route = route.firstChild; }
return route;
}),
filter((route) => route.outlet === 'primary'),
mergeMap((route) => route.data)).subscribe((event) => {
this.titleService.setTitle(event['title'] + ' | Sticos Design');
});
} else {
this.titleService.setTitle(title + ' | Sticos Design');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment