Skip to main content
Version: 5.x.x

Translating (Angular)

Check our Angular example application

You can use pipe, t component, or translation methods to translate strings in Angular.

Using pipe

To translate a string using translate pipe.

<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 some message formatter.

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

You can also provide a default value.

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

To disable wrapping, provide a noWrap option.

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

Element with t attribute

You can also use element with t attribute. 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 some message formatter.

<p t key="Peter has n dogs" [params]="{ name: 'John Doe' }"></p>

You can provide a default value using the default attribute

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

Using translation methods

To translate texts in your component code, use translate or instant method.

These methods are part of TranslateService which can be injected using dependency injection:

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 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 some reason, you can use instant method.

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

Both instant and translate methods accept the same parameters as tolgee.t. So you can use all its features.

danger

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