How to dynamically set page titles in the browser tab in Angular 8?

Viewed 1303

I have a scenario like there's a list of employees in the developing application. When I click one employee name, it navigates to that employee's details. Whenever i navigate to each employee's details, my browser title should display information like “Employee Name: Employee Number". So that the title should change according to the employee.

Suppose I am also having list of departments and there the same thing should happen; if i navigate to department component browser title should display information like “Department Name: Department Number”.

Please suggest how to achieve this in generic way instead of setting title in each component.

1 Answers

Angular provides a TitleService that allows you to change the title of the page at any given time.

It is here:

import { Title } from '@angular/platform-browser';

Either in a custom service, you can listen for route changes, fetch the bottom-most route and change the title based on the data passed on the router.

public title: string = '';

constructor(private router: Router,  
    private activatedRoute: ActivatedRoute,  
    private titleService: Title) {}  

ngOnInit() {  
    this.router.events.pipe(  
        filter(event => event instanceof NavigationEnd),  
    ).subscribe(() =>
        this.titleService.setTitle(this.title));
}  

getChild(activatedRoute: ActivatedRoute) {  
    if (activatedRoute.firstChild) {  
        return this.getChild(activatedRoute.firstChild);  
    } else {  
        return activatedRoute;  
    }
}

You can then set the title you want for each component.

constructor(private customService: CustomService) {
    this.customService.title = 'Whatever you want';
}
Related