Skip to content

ngx-translate TranslateService API Reference

To use the TranslateService in your components, you can inject it using Angular’s inject() function:

import { inject } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
export class MyComponent {
private translate = inject(TranslateService);
// Now you can use this.translate to access the service methods
}
  • use - Set the current language and load translation file(s) if not yet done
  • setFallbackLang - Set and load the fallback language. Strings of this language are displayed if keys are missing in the current language.
  • getFallbackLang - Get the fallback language
  • getCurrentLang - Get the current language
  • getLangs - Get list of languages loaded - or set by addLangs
  • addLangs - Add language to the list of languages (does not load that language)
  • stream - Get an Observable for the given translation key, fires when translations are loaded or the language changed.
  • instant - Translate text once, returns a string immediately if the language is already loaded.
  • get - Get an Observable for the given translation key, fires once as soon as the translation is loaded.
  • getStreamOnTranslationChange - Get an Observable for the given translation key, monitors changes of the translation (e.g. when new translations are set or the language changes)
  • set - Set single translation
  • reloadLang - Reload translations for the given language
  • resetLang - Remove translations for the given language
  • setTranslation - Set translations for a language
addLangs(langs: string[])

You can add new languages to your list. This won’t invoke the loader to retrieve them.

get(key: string|string[], interpolateParams?: object): Observable<Translation|TranslationObject>

Retrieves the translation(s) for the specified key(s).

  • key: A single string or an array of strings representing the translation key(s) to retrieve.
  • interpolateParams (optional): An object containing parameter values to interpolate within the translation strings.

An Observable that emits the translated string(s):

  • If a single key is provided, it emits the translated message as Translation.
  • If an array of keys is provided, it emits an object { [key: string]: Translation } mapping each key to its translated string.
  • If a translation for a given key is not found, the key itself is returned (unless a fallback mechanism is configured).

The Observable will emit once the translation file has finished loading and the translation(s) are available. After emitting, the Observable completes.

Getting a single translation

translate.get('HELLO')
.subscribe((res: string) => {
console.log(res); // Output: 'Hello'
});

Getting multiple translations

translate.get(['HELLO', 'WELCOME'])
.subscribe((translations: { [key: string]: string }) => {
console.log(translations);
// Output: { HELLO: 'Hello', WELCOME: 'Welcome' }
});

Using interpolateParams

translate.get('WELCOME_USER', { username: 'John' })
.subscribe((res: string) => {
console.log(res); // Output: 'Welcome, John!'
});
getBrowserCultureLang(): string | undefined

Returns the browser’s full culture language code (e.g., "en-US")

Returns the browser’s culture language setting if available, or undefined if it cannot be determined.

const lang = translate.getBrowserCultureLang();
console.log(lang); // Output: "de-DE"
getBrowserLang(): string | undefined

Get the language set in the browser.

Returns the browser’s current language setting if available, or undefined if it cannot be determined.

const lang = translate.getBrowserLang();
console.log(lang); // Output: "de"
getFallbackLang(): string | null

Returns the fallback language code that has been set as the fallback language.

string | null: The language code of the fallback language, or null if none is set.

The getFallbackLang() method retrieves the fallback language that has been set using the setFallbackLang() method. This is the language code that the TranslateService uses as a fallback when a translation key is missing in the current language.

const fallbackLang = translate.getFallbackLang();
console.log('Fallback language:', fallbackLang);
// Output: 'en'
getCurrentLang(): Language

Returns the currently active language code.

Language: The language code of the currently active language.

The getCurrentLang() method retrieves the language code that is currently being used by the TranslateService for translations. This is the language that was set using the use() method.

const currentLang = translate.getCurrentLang();
console.log('Current language:', currentLang);
// Output: 'en'
getLangs(): readonly Language[]

Returns an array of currently available languages. The list can be extended calling setDefaultLang, use, setTranslation oraddLangs.

getStreamOnTranslationChange(key: string|string[], interpolateParams?: object):
Observable<Translation|TranslationObject>

Returns an Observable stream of translated values for the specified key(s). Unlike get(), this method emits a new value whenever the translations change, such as when new translations are loaded or when onTranslationChange events occur.

  • key: A string or an array of strings representing the translation key(s) to retrieve.
  • interpolateParams (optional): An object containing parameters to interpolate within the translation strings.

An Observable that emits the translated string(s):

  • If a single key is provided, it emits the translated message as Translation.
  • If an array of keys is provided, it emits an object { [key: string]: Translation } mapping each key to its translated string.
  • If a translation for a given key is not found, the key itself is returned (unless a fallback mechanism is configured).

The Observable will emit:

  • Immediately with the current translation(s) once the translation file has finished loading.
  • Whenever the translation changes due to events like language updates or new translations being added.
  • The Observable does not complete on its own; it remains active to emit future translation changes. You should unsubscribe to prevent memory leaks when the stream is no longer needed.

Subscribing to a single translation key

const subscription = translate
.getStreamOnTranslationChange('HELLO')
.subscribe((res: string) => {
console.log(res);
// Output: 'Hello' (and updates if the translation changes)
});

Subscribing to multiple translation keys

const subscription = translate
.getStreamOnTranslationChange(['HELLO', 'WELCOME'])
.subscribe((translations: { [key: string]: string }) => {
console.log(translations);
// Output: { HELLO: 'Hello', WELCOME: 'Welcome' }
// (and updates if translations change)
});

Using interpolateParams

const subscription = translate
.getStreamOnTranslationChange('WELCOME_USER', { username: 'John' })
.subscribe((res: string) => {
console.log(res);
// Output: 'Welcome, John!' (and updates if translations change)
});
// Remember to unsubscribe when done
subscription.unsubscribe();
instant(key: string|string[], interpolateParams?: object): Translation|TranslationObject

Retrieves the translated value(s) for a key (or an array of keys) instantly.

  • key: A string or an array of strings representing the translation key(s) to retrieve.
  • interpolateParams (optional): An object containing parameters to interpolate within the translation strings.

An Observable that emits the translated string(s):

  • If a single key is provided, it emits the translated message as Translation.
  • If an array of keys is provided, it emits an object { [key: string]: Translation } mapping each key to its translated string.
  • If a translation for a given key is not found or not yet loaded, the key itself is returned (unless a fallback mechanism is configured).

Translating a single translation key

const res = translate.instant('HELLO');
console.log(res);
// Output: 'Hello' (if translation is already loaded)

Translating multiple keys

const res = translate.instant(['HELLO', 'WELCOME']);
console.log(res);
// Output: { HELLO: 'Hello', WELCOME: 'Welcome' }
// (if translation is already loaded)

Translating a key with interpolation

const res = translate.instant('WELCOME_USER', { username: 'John' });
console.log(res);
// Output: 'Welcome, John!' (if translation is already loaded)
reloadLang(lang: string): Observable<InterpolatableTranslationObject>

Reloads the translations for the specified language by resetting (calling resetLang()) and fetching them anew using the current loader.

  • lang: The language to reload

An Observable that completes after the translations are loaded.

translate.reloadLang('es').subscribe((translations) => {
console.log('Spanish translations reloaded:', translations);
// Output: Spanish translations reloaded:
// { 'HELLO': 'Hola', 'GOODBYE': 'Adiós', ... }
});
resetLang(lang: string): void

Removes the translations for the specified language.

  • lang: The language to remove
translate.resetLang('es');
set(key: string, translation: InterpolatableTranslationObject, lang?: string): void

Assigns a translation value to a specific key.

  • key: A string representing the translation key(s) to set. The key can contain ”.” to create a hierarchy of translations (e.g., hello.world), allowing for nested translation objects.

  • translation: The translation for this key. Passed through the TranslateCompiler for preparing interpolations based on the provided translation object.

  • lang (optional): The language to set the key for. If not provided, the key is set on the currently active language.

This method sets a translation value for a given key in the specified language. If the language does not exist in the translation store, it is added automatically. The key can be hierarchical, using ”.” to indicate nesting (e.g., hello.world will create a structure where world is a child of hello).

The translation object is processed by TranslateCompiler, which prepares the translation values for interpolation. This ensures that any dynamic elements within the translation string are correctly handled.

If the key already exists, the translation is overwritten. Once the update is complete, onTranslationChange is triggered to notify all observers about the change.

Overwriting an existing key will replace the current value without merging nested structures.

Setting a single translation for the default language

translate.set('HELLO.WORLD', "Hallo World!");

Setting a translation for German:

translate.set('HELLO.WORLD', "Hallo Welt!", "de");
setFallbackLang(lang: string): Observable<InterpolatableTranslationObject>

Sets the fallback language to be used when a translation is missing in the current language.

  • lang: A string representing the language code to set as the fallback language.

An Observable that emits the translations object for the specified language and completes when the loading is finished.

The setFallbackLang() method specifies the fallback language that the TranslateService will use to look up translations when a key is not found in the current language.

This ensures that your application can gracefully display translations from a fallback language rather than showing missing keys.

Calling this method will:

  • Set the fallback language for translations.
  • Use the loader to retrieve translations for the specified language if they haven’t been loaded yet.
  • Update the list of available languages, which can be retrieved using getLangs().
  • Emit an onFallbackLangChange event to notify subscribers.
translate.setFallbackLang("en").subscribe((translations) => {
console.log('Fallback language set to English');
console.log('English translations:', translations);
});
setTranslation(lang: string, translations: InterpolatableTranslationObject, shouldMerge: boolean = false)

Manually sets an object of translations for a given language, set shouldMerge to true if you want to append the translations instead of replacing them.

Using setTranslation updates the list of available languages which can be retrieved using getLangs.

stream(key: string|string[], interpolateParams?: object):
Observable<Translation|TranslationObject>

Returns an Observable stream of translated values for the specified key(s). Unlike get(), this method emits a new value whenever the language changes (onLangChange() event), such as when calling use().

  • key: A string or an array of strings representing the translation key(s) to retrieve.
  • interpolateParams (optional): An object containing parameters to interpolate within the translation strings.

An Observable that emits the translated string(s):

  • If a single key is provided, it emits the translated message as Translation.
  • If an array of keys is provided, it emits an object { [key: string]: Translation } mapping each key to its translated string.
  • If a translation for a given key is not found, the key itself is returned (unless a fallback mechanism is configured).

The Observable will emit:

  • Immediately with the current translation(s) once the translation file has finished loading.
  • Whenever the language changes due to events like language updates
  • The Observable does not complete on its own; it remains active to emit future translation changes. You should unsubscribe to prevent memory leaks when the stream is no longer needed.

Subscribing to a single translation key

const subscription = translate.stream('HELLO')
.subscribe((res: string) => {
console.log(res);
// Output: 'Hello' (and updates if the translation changes)
});

Subscribing to multiple translation keys

const subscription = translate.stream(['HELLO', 'WELCOME'])
.subscribe((translations: { [key: string]: string }) => {
console.log(translations);
// Output: { HELLO: 'Hello', WELCOME: 'Welcome' }
// (and updates if translations change)
});

Using parameter interpolation:

const subscription = translate.stream('WELCOME_USER', { username: 'John' })
.subscribe((res: string) => {
console.log(res);
// Output: 'Welcome, John!' (and updates if translations change)
});
// Remember to unsubscribe when done
subscription.unsubscribe();
use(lang: string): Observable<InterpolatableTranslationObject>

Changes the currently active language to the specified language code. This method triggers the loader to retrieve the translations for the new language if they have not been loaded yet.

  • lang: A string representing the language code to set as the current language.

An Observable that emits the translations object for the specified language and completes when the loading is finished.

The use() method switches the application’s current language to the one provided. If the translations for the specified language are not already loaded, it will use the configured loader to fetch them. This method also updates the list of available languages, which can be accessed using getLangs().

Since ngx-translate v16, use() now has a deterministic behavior. When calling this function in quick succession, the most recent call sets the current language, regardless of which language’s translation file finishes loading first.

  • Impact on Existing Subscriptions: Components or services subscribed to translation observables (e.g., via get() or stream()) will receive updates when the language changes.
  • Available Languages: The specified language will be added to the list of available languages accessible via getLangs() if it’s not already included.
  • Current Language: The current language is set immediately on the first call to use(). Afterward, it is only updated once the translation file for the most recent call of use() finishes loading.
// Switch to French language
translate.use('fr').subscribe((translations) => {
console.log('Current language is now French.');
console.log('French translations:', translations);
// Output: French translations: { 'HELLO': 'Bonjour', 'GOODBYE': 'Au revoir', ... }
});

An Observable that emits language change events. A LangChangeEvent object is emitted, containing the following properties:

NameTypeDescription
langstringThe code of the newly activated language.
translationsInterpolatableTranslationObjectAn object containing the updated translations.

Example:

translate.onLangChange.subscribe((event: LangChangeEvent) => {
console.log('Language changed to:', event.lang);
console.log('Translations:', event.translations);
});

An Observable that emits translation change events.

A TranslationChangeEvent object is emitted, containing the following properties:

NameTypeDescription
langstringThe code of the currently active language.
translationsInterpolatableTranslationObjectAn object containing the updated translations.

Example:

translate.onTranslationChange.subscribe((event: TranslationChangeEvent) => {
console.log('Translations changed for language:', event.lang);
console.log('Updated translations:', event.translations);
});

An Observable that emits fallback language change events.

A FallbackLangChangeEvent object is emitted, containing the following properties:

NameTypeDescription
langstringThe code of the newly set fallback language.
translationsInterpolatableTranslationObjectAn object containing the fallback translations.

Example:

translate.onFallbackLangChange.subscribe((event: FallbackLangChangeEvent) => {
console.log('Fallback language changed to:', event.lang);
console.log('Fallback translations:', event.translations);
});

Reason: We’ve deprecated this method because the default caused confusion with the users. This fallback describes way better what it does.

Use getFallbackLang() instead:

const lang = translate.getDefaultLang()
const lang = translate.getFallbackLang()

v17 also corrects the API.

  • The getDefaultLang() on older versions returned a string, which was practically not true if no default lang was set - in this case, it silently returned undefined or null.
  • getFallbackLang() returns a Language (which is an alias for string) or null if not set.

Reason: We’ve deprecated this method because the default caused confusion with the users. This fallback describes way better what it does.

Use setFallbackLang() instead:

translate.setDefaultLang('en');
translate.setFallbackLang('en');

Reason: The getTranslation() function, which returned an object containing all translations for a given language in a raw state, has been deprecated. This function might return not only text nodes but also functions (when using a custom TranslateCompiler) for text interpolation.

We no longer see a practical use case for relying on this function.

To retrieve specific translations, use functions like get() or instant() to access the translations you need directly.

This provides more control and efficiency in handling translation retrieval.

Reason: The properties and methods implemented exactly the same functionality.

The langs property provided direct access to the list of available languages. Use getLangs() method instead:

const availableLanguages = translate.langs;
const availableLanguages = translate.getLangs();

Reason: The properties and methods implemented exactly the same functionality.

The currentLang property provided direct access to the currently active language. Use getCurrentLang() method instead:

const current = translate.currentLang;
const current = translate.getCurrentLang();

Reason: The properties and methods implemented exactly the same functionality. We’ve deprecated this method because the default caused confusion with the users. This fallback describes way better what it does.

The defaultLang property provided direct access to the fallback language. Use getFallbackLang() method instead:

const fallback = translate.defaultLang;
const fallback = translate.getFallbackLang();

Reason: We’ve deprecated this method because the default caused confusion with the users. This fallback describes way better what it does.

The onDefaultLangChange observable has been renamed for clarity. Use onFallbackLangChange instead:

translate.onDefaultLangChange.subscribe((event) => {
translate.onFallbackLangChange.subscribe((event) => {
console.log('Fallback language changed:', event.lang);
});
Imprint Privacy