Manage Angular page titles translation
Translate pages’ titles using the Streamlined page title feature!
Angular v14.1 is here !!
In the beginning of June 2022, the Angular team announced the release of Angular v14. This version brings some cool features like: Standalone Components, Typed Forms, and more (learn about the new features in this Article).
In this article, I will be talking about how to manage page titles translation using a new feature in Angular: Streamlined page title.
Streamlined page title (the built-in TitleStrategy)
This super cool feature makes it much easier to manage pages titles. To add a title to your page, simply use the new Routes attribute ‘title’, and Angular will do the magic !
Here is an example on how does it work :
In this example, Angular -TitleStrategy- will set the page title after successfully navigating from a page to another based on the primary router outlet.
If you want to define a prefix for your pages’ titles, you may have to override the TitleStrategy.
Translate page titles:
If your application is multi-languages, you’ll need to translate the pages’ titles too. In this paragraph I’ll show you how to do that :
To translate the application, I’ll be using the ngx-translate library.
npm install @ngx-translate/core @ngx-translate/http-loader
I’ll be translating the app into 3 languages, so I’ll create 3 translation files; one for each language:
en.json
{
"TOOLBAR": {
"WELCOME": "Welcome",
"PAGE_1": "Page 1",
"PAGE_2": "Page 2"
},
"PAGE_1": {
"TITLE": "Page title 1"
},
"PAGE_2": {
"TITLE": "Page title 2"
}
}
fr.json
{
"DEFAULT_TITLE": "Home",
"TOOLBAR": {
"WELCOME": "Bienvenue",
"PAGE_1": "Page 1",
"PAGE_2": "Page 2"
},
"PAGE_1": {
"TITLE": "Titre de la page 1"
},
"PAGE_2": {
"TITLE": "Titre de la page 2"
}
}
ar.json
{
"TOOLBAR": {
"WELCOME": "مرحبا",
"PAGE_1": "الصفحة 1",
"PAGE_2": "الصفحة 2"
},
"PAGE_1": {
"TITLE": "عنوان الصفحة 1"
},
"PAGE_2": {
"TITLE": "عنوان الصفحة 2"
}
}
I will not go into details of how to use ngx-translate lib, if you are not familiar with it, I recommend you this great article : Angular + @ngx-translate + Typings by Carlos Caballero.
To translate the pages’ titles, we have to override the Angular behaviour of page titles (TitleStrategy); by creating a CustomPageTitleStrategy class that will get the title translation key and set the correct translated title.
To override the TitleStrategy, we need simply to add it to the app.module providers :
{ provide: TitleStrategy, useClass: CustomPageTitleStrategy }
And finally, we need to edit the titles in our routes : so instead of a page title, we‘ll replace it with the title translation key as following :
Here is a demo project : https://angular-page-title-translate.stackblitz.io
The project on Github :
https://github.com/adnanelamghari/angular-page-title-translate