DEV Community

jcarloscandela
jcarloscandela

Posted on

1

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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (1)

Collapse
 
artursbuls profile image
ArtursBuls

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more