DEV Community

jcarloscandela
jcarloscandela

Posted on

How to translate web page titles with Angular

Since Angular 15 we have the possibility to modify the title of the page from the routing. It is as simple as doing the following:

const routes: Routes = [
    {
        path: 'login',
        component: LoginComponent,
        title: 'Login'
    }
];
Enter fullscreen mode Exit fullscreen mode

It is a very comfortable way of giving a title to any page of our project and being able to know where you were when we changed tabs in the browser. What if we want to translate the title?

The best way is to create a resolver. What is an Angular resolver?
A resolver allows us to get data before navigating to the new route.

To make a resolver we have to implement the Resolve interface. We also need a service to translate our translations keys, in this case I am using the package @ngx-translate/core

custom-title.resolver.ts

import { Injectable } from '@angular/core';
import { Resolve, ActivatedRouteSnapshot } from '@angular/router';
import { TranslateService } from '@ngx-translate/core';

@Injectable({ providedIn: 'root' })
export class CustomTitleResolver implements Resolve<string> {
    constructor(
        private _translateService: TranslateService,
    ) {}

    resolve(route: ActivatedRouteSnapshot): Promise<string> {
        if (!route.data.titleKey) {
            return Promise.resolve('Default title');
        }

        return Promise.resolve(
            this._translateService.instant(route.data.titleKey)
        );
    }
}

Enter fullscreen mode Exit fullscreen mode

Now we go back to our routing file, we add the resolver and we have to pass the key of our translation. It will look like this:

const routes: Routes = [
    {
        path: 'login',
        component: LoginComponent,
        title: CustomTitleResolver,
        data: { titleKey: 'Login'}
    }
];
Enter fullscreen mode Exit fullscreen mode

With all this, we now have a way to translate all the titles of our application, we just have to add the Resolver and the translation key to each of the routes. I hope it helps you, regards.

Top comments (1)

Collapse
 
artursbuls profile image
ArtursBuls

Nice code.
Press F5 (reload the page), and title translation breaks.