How to Create a Dynamic Page Title in Angular

Or Anaki
HiBob Engineering & Security Blog
2 min readOct 24, 2022

--

Something we often overlook when we build a web app is the page title. The user sees the page title in the browser tab and it helps them navigate the app.
Some reasons for using specific page titles are to show users which page they’re on within the app, and to assist them when bookmarking a particular page.

Change the page title using the Title service

Angular provides us with a Title service, and we can use that service to change the page title to something meaningful to our users.

The title service has two methods we can use:
getTitle(){} - Get the title of the current HTML document
setTitle(){} -Set the title of the current HTML document

Let's see that in action 😃

In the above example, we defined a title property inside the route data for each route, and in the app component class, we listened to the router event.
We used the setTitle method from the Title service when we navigated to a particular page to update the app title.

Update a page title with Angular V14+ 🚀

From angular version 14, we can update the page title more easily.
Angular expose us to the optional title property in the route definition.

As we saw in the code above, we can change the page title by setting a hardcoded string or using a resolver class for more dynamic page titles.

Suppose we want the app prefix to appear in all the page titles. In that case, we need to create a class that implements the abstract TitleStrategy, modify our prefix text, and sign the class we created in the DI (dependencies injection) system.
Let's see that in action.

In the code above we can see that instead of using the angular TitleStrategy provider, we use our AppTitlePrefix class that extends the TitleStrategy abstract class, and add the App prefix to the title.

Thanks for reading this article, and I hope it was helpful to you all 😀

--

--