TranslateService API
- use - Set the current language and load translation file(s) if not yet done
- setDefaultLang - Set and load the fallback language. Strings of this language are displayed if keys are missing in the current language.
- getDefaultLang - Get the fallback 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)
- getBrowserCultureLang - Get the browser culture language (e.g.
de-DE
) - getBrowserLang - Get the browser language (e.g.
de
)
- 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[])
Add new languages to the list. This does not invoke the loader to retrieve the languages.
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
translateService.get('HELLO') .subscribe((res: string) => { console.log(res); // Output: 'Hello' });
Getting multiple translations
translateService.get(['HELLO', 'WELCOME']) .subscribe((translations: { [key: string]: string }) => { console.log(translations); // Output: { HELLO: 'Hello', WELCOME: 'Welcome' } });
Using interpolateParams
translateService.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 = translateService.getBrowserLang();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 = translateService.getBrowserLang();console.log(lang); // Output: "de"
getDefaultLang(): string
Returns the default language code that has been set as the fallback language.
string: The language code of the default fallback language.
The getDefaultLang()
method retrieves the default language that has been set
using the setDefaultLang()
method. This is the language code that the TranslateService
uses as a fallback when a translation key is missing in the current language.
const defaultLang = translateService.getDefaultLang();console.log('Default language:', defaultLang);// Output: 'en'
getLangs(): string[]
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 = translateService .getStreamOnTranslationChange('HELLO') .subscribe((res: string) => { console.log(res); // Output: 'Hello' (and updates if the translation changes) });
Subscribing to multiple translation keys
const subscription = translateService .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 = translateService .getStreamOnTranslationChange('WELCOME_USER', { username: 'John' }) .subscribe((res: string) => { console.log(res); // Output: 'Welcome, John!' (and updates if translations change) });
// Remember to unsubscribe when donesubscription.unsubscribe();
The getTranslation()
function, which returned an object containing all translations
for a given language, 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.
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 = translateService.instant('HELLO');console.log(res);// Output: 'Hello' (if translation is already loaded)
Translating multiple keys
const res = translateService.instant(['HELLO', 'WELCOME']);console.log(res);// Output: { HELLO: 'Hello', WELCOME: 'Welcome' }// (if translation is already loaded)
Translating a key with interpolation
const res = translateService.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.
translateService.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
translateService.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 theTranslateCompiler
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
translateService.set('HELLO.WORLD', "Hallo World!");
Setting a translation for German:
translateService.set('HELLO.WORLD', "Hallo Welt!", "de");
setDefaultLang(lang: string): void
Sets the default language to be used as a fallback when a translation is missing in the current language.
lang
: A string representing the language code to set as the default language.
The setDefaultLang()
method specifies the default 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 default 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()
.
translateService.setDefaultLang("en");
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 = translateService .stream('HELLO') .subscribe((res: string) => { console.log(res); // Output: 'Hello' (and updates if the translation changes) });
Subscribing to multiple translation keys
const subscription = translateService .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 = translateService .stream('WELCOME_USER', { username: 'John' }) .subscribe((res: string) => { console.log(res); // Output: 'Welcome, John!' (and updates if translations change) });
// Remember to unsubscribe when donesubscription.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()
orstream()
) 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 ofuse()
finishes loading.
// Switch to French languagetranslateService.use('fr').subscribe((translations) => { console.log('Current language is now French.'); console.log('French translations:', translations); // Output: French translations: { 'HELLO': 'Bonjour', 'GOODBYE': 'Au revoir', ... }});
The TranslateService
exposes the following properties:
Property | Description |
---|---|
langs | List of languages. string[] |
translations | Object containing translations per language any |
currentLang | The language currently in use. string |
defaultLang | The default (fallback) language. string |
currentLoader | The current instance of the loader (static loader by default). TranslateLoader |
onLangChange | Event emitter that fires when the language changes. EventEmitter<LangChangeEvent> |
onTranslationChange | Event emitter that fires when the translations change. EventEmitter<TranslationChangeEvent> |
onDefaultLangChange | Event emitter that fires when the default language changes. EventEmitter<DefaultLangChangeEvent> |
An EventEmitter
that listens for language change events. A LangChangeEvent
object is emitted, containing the following properties:
Name | Type | Description |
---|---|---|
lang | string | The code of the newly activated language. |
translations | any | An object containing the updated translations. |
Example:
onLangChange.subscribe((event: LangChangeEvent) => { // do something);
An EventEmitter
that listens for translation change events.
A TranslationChangeEvent
object is emitted, containing the following properties:
Name | Type | Description |
---|---|---|
lang | string | The code of the currently active language. |
translations | any | An object containing the updated translations. |
Example:
onTranslationChange.subscribe((event: TranslationChangeEvent) => { // do something);
An EventEmitter
that listens for default language change events.
A DefaultLangChangeEvent
object is emitted, containing the following properties:
Name | Type | Description |
---|---|---|
lang | string | The code of the newly set default language. |
translations | any | An object containing the default translations. |
Example:
onDefaultLangChange.subscribe((event: DefaultLangChangeEvent) => { // Do something with the new default language or translations});