Skip to main content
Version: 5.x.x

Translating

You can implement translation in your Angular application in the following ways.

Translate pipe

You can translate a string using the translate pipe. It accepts specific parameters and an optional default value.

<h1>{{'hello_world' | translate}}</h1>

To provide parameters for translation, pass them as the first parameter of the translate pipe.

info

To enable parameter interpolation, you need to use a message formatter.

<h1>{{'hello' | translate:{ name: 'John Doe' }}}</h1>

You can also provide a default value.

// with params
<h1>{{'hello' | translate:{ name: 'John Doe' }:'Default!'}}</h1>

// or without params
<h1>{{'hello' | translate:'Default!'}}</h1>

To disable wrapping, provide a noWrap option.

<h1>{{ 'hello' | translate:{ noWrap: true } }}</h1>

t attribute

You can also use a t attribute with an element for translation. Angular will render Tolgee component with t attribute selector.

<h1 t key="providing_default_values"></h1>

To provide parameters for translation, pass them via the params attribute.

info

To enable parameter interpolation, you need to use a message formatter.

<p t key="using_t_with_params" [params]="{ name: 'John Doe' }"></p>

You can also provide a default value using the default attribute.

<p t key="using_t_with_default" default="This is default"></p>

Translation methods

To translate texts in your component code, you can use translate or instant methods.

These methods are part of TranslateService which can be injected using dependency injection as shown in the following example.

import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@tolgee/ngx';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
constructor(private translateService: TranslateService) {}

helloWorld: string;

async ngOnInit(): Promise<void> {
this.translateService
.translate('hello_world')
.subscribe((r) => (this.helloWorld = r));
}
}

translate method returns an Observable. As a result, the provided listener is called every time the translation changes due to language changes or other reasons.

this.translateService
.get('hello_world')
.subscribe((r) => (this.helloWorld = r));

If you are unable to use this asynchronous approach for any reason, you can use the instant method.

danger

Don't overuse the instant method. Whenever possible, use the translate method. When translations are not loaded, instant method will not provide a valid result.

this.helloWorld = this.translateService.instant('hello_world');

Both the instant and translate methods accept the same parameters as tolgee.t.

tip
You can also check the Angular example application to learn more.