Skip to content

Configuration

ngx-translate is configured using standalone provider functions. The legacy TranslateModule.forRoot/forChild API was removed in v18; see NgModules Support for the transition stub.

For Angular version compatibility, see Angular Compatibility.

Both provider functions accept retry and the same plugin slots (loader, compiler, parser, missingTranslationHandler); the root variant adds language fields (fallbackLang, lang). The plugin slots accept the TranslateProvider shape: a regular Angular Provider object, the matching provideTranslate* helper, a bare class, or a bare factory function. Bare classes and factories are auto-wrapped under the correct DI token (see Bare-class auto-wrap warning).

Configures the root TranslateService at app bootstrap. Use it once in appConfig (or in bootstrapApplication providers).

app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { provideTranslateService, provideTranslateLoader } from '@ngx-translate/core';
import { provideTranslateHttpLoader } from '@ngx-translate/http-loader';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
provideTranslateService({
loader: provideTranslateHttpLoader({ prefix: '/assets/i18n/' }),
fallbackLang: 'en',
lang: 'de',
}),
],
};

All properties are optional. Plugin slots fall back to no-op / default implementations when omitted.

NameTypeDescription
fallbackLangstringFallback language used when a translation is missing in the current language.
langstringInitial active language on startup.
retrynumber | TranslateRetryConfigRetries after a failed language load. Defaults to 0 (disabled). The policy object is available since v18.1. See Retrying failed language loads.
loaderTranslateProviderProvides a TranslateLoader. Defaults to a no-op loader; provide setTranslation()-loaded data if you don’t use one.
compilerTranslateProviderProvides a TranslateCompiler that pre-processes translations after loading. Defaults to a no-op.
parserTranslateProviderProvides a TranslateParser that interpolates {{ placeholder }} values. Defaults to the bundled TranslateDefaultParser.
missingTranslationHandlerTranslateProviderProvides a MissingTranslationHandler. Defaults to returning the key.

If fallbackLang is unset and a key is missing in the current language, the missingTranslationHandler is invoked directly.

Creates a connected child service with its own store and (optionally) its own loader. Child services delegate currentLang / fallbackLang to the root and walk up the parent chain when a key isn’t found locally. Use this inside route or component providers, typically for lazy-loaded features.

For an isolated child (no parent fallback, own language state), use provideTranslateService() again on the route instead.

feature.routes.ts
import { Routes } from '@angular/router';
import { provideChildTranslateService } from '@ngx-translate/core';
import { provideTranslateHttpLoader } from '@ngx-translate/http-loader';
export const routes: Routes = [
{
path: 'feature',
providers: [
provideChildTranslateService({
loader: provideTranslateHttpLoader({ prefix: '/assets/i18n/feature/' }),
}),
],
loadChildren: () => import('./feature/feature.routes'),
},
];
NameTypeDescription
retrynumber | TranslateRetryConfigRetries for this child’s own language loads. Defaults to 0, independently of the root. The policy object is available since v18.1. See Retrying failed language loads.
loaderTranslateProviderOverride the loader for this child only.
compilerTranslateProviderOverride the compiler for this child only.
parserTranslateProviderOverride the parser for this child only.
missingTranslationHandlerTranslateProviderOverride the handler for this child only.

Unspecified slots use the parent service’s plugins. Most child services only override loader to point at a feature-specific translation file. See Concepts → Hierarchical Services for the chain semantics.

Set retry to the number of retries allowed after the initial load attempt. The default is 0, so failed loads are not retried automatically. For example, retry: 2 allows up to three attempts, with a fixed 100 ms delay before each retry. This can help recover from transient network or response-parsing errors; it does not repair invalid JSON or missing files.

With @ngx-translate/http-loader, you must also set failOnError: true. The default HTTP loader catches request errors and returns an empty object for each failed resource, leaving the service with no error to retry.

app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import { provideTranslateService } from '@ngx-translate/core';
import { provideTranslateHttpLoader } from '@ngx-translate/http-loader';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
provideTranslateService({
lang: 'en',
retry: 2,
loader: provideTranslateHttpLoader({
prefix: '/assets/i18n/',
failOnError: true,
}),
}),
],
};

The option applies to initial loads, language switches, fallback-language loads, and reloadLang(). isLoading() stays true during retry delays. If every attempt fails, the load Observable emits the error through the existing error handling. A later call can start a fresh load.

Configure retry separately in provideChildTranslateService() for a child’s own loader; the root’s retry count is not inherited. The same failOnError: true requirement applies. With a multi-resource HTTP loader, a retry repeats the whole language load, including resources that succeeded on the previous attempt.

Pass a TranslateRetryConfig object to choose the retry delay and which errors to retry. Both provider functions accept this type, exported from @ngx-translate/core.

PropertyTypeBehavior
countnumberRequired maximum number of retries after the initial attempt. Zero or negative values disable retries and both callbacks.
delaynumber | ((error: unknown, retryAttempt: number) => number)Delay in milliseconds. Defaults to 100. The first retry has retryAttempt = 1; numbering restarts for each language load.
shouldRetry(error: unknown) => booleanRuns when retries remain, before calculating the delay. Defaults to retrying every error. Returning false immediately propagates the original error without calling delay.

Use retry: { count: 2, delay: 500 } for a fixed delay. To wait longer after each failure and retry only selected HTTP errors:

app.config.ts
import { ApplicationConfig } from '@angular/core';
import { HttpErrorResponse, provideHttpClient } from '@angular/common/http';
import { provideTranslateService } from '@ngx-translate/core';
import { provideTranslateHttpLoader } from '@ngx-translate/http-loader';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
provideTranslateService({
lang: 'en',
retry: {
count: 2,
delay: (_error, retryAttempt) => 250 * 2 ** (retryAttempt - 1),
shouldRetry: (error) =>
error instanceof HttpErrorResponse &&
(error.status === 0 || error.status === 429 || error.status >= 500),
},
loader: provideTranslateHttpLoader({ failOnError: true }),
}),
],
};

This example waits 250 ms before the first retry and 500 ms before the second. A 404 fails immediately. Both callbacks receive the original loader error as unknown; check its type before reading properties. HTTP loaders still require failOnError: true, because permissive failures return an empty object without invoking either callback.

A fixed or calculated delay must be a finite number from 0 to 2,147,483,647 milliseconds. TypeScript rejects string delays and callbacks that return strings. The service checks the value before scheduling each retry; an invalid value terminates the load with a RangeError. If delay or shouldRetry throws, the load fails with that exception. Exhausting count propagates the last loader error.

Concurrent callers for the same language on one service share the load and retry sequence. isLoading() stays true during retry delays. With a policy object, the failed load Observable keeps its final error: subscribing again, including through RxJS retry(), does not start another request. Call use(), setFallbackLang(), or reloadLang() again to start a fresh load. This also works inside an error handler. Numeric retry settings retain their existing behavior, including the fixed 100 ms delay and resubscription after an error.

The service copies the policy at construction. Later changes to its properties do not affect active or future loads. Configure each child or isolated service separately; a child does not inherit its parent’s retry count or callbacks.

Retries in a custom loader or HTTP interceptor combine with service retries. Two retries at each level can make up to nine requests for one resource: three service attempts, each allowing three loader attempts. See Retrying failed loads for custom-loader requirements.

Each plugin ships with a provideTranslate* helper. The helpers accept either a class or a factory function:

import {
provideTranslateLoader,
provideTranslateCompiler,
provideTranslateParser,
provideMissingTranslationHandler,
} from '@ngx-translate/core';

Use the class form when Angular’s constructor DI can satisfy every dependency of your plugin.

app.config.ts
provideTranslateService({
loader: provideTranslateLoader(MyTranslateLoader),
compiler: provideTranslateCompiler(MyCompiler),
parser: provideTranslateParser(MyParser),
missingTranslationHandler: provideMissingTranslationHandler(MyHandler),
})

Use the factory form when your plugin needs runtime arguments (e.g. a custom path) or values that come from inject(). New in v18.

provideTranslateService({
loader: provideTranslateLoader(() => new MyLoader(inject(HttpClient), '/i18n')),
compiler: provideTranslateCompiler(() => new MyCompiler({ icu: true })),
})

The factory runs inside Angular’s injection context, so you can call inject() freely.

The HTTP loader fetches JSON translation files. v18 adds built-in multi-resource support. Pass a resources array to load and deep-merge several sources per language.

app.config.ts
import { provideTranslateHttpLoader } from '@ngx-translate/http-loader';
provideTranslateService({
loader: provideTranslateHttpLoader({
prefix: '/assets/i18n/',
suffix: '.json',
enforceLoading: false,
useHttpBackend: false,
}),
})
NameTypeDefaultDescription
prefixstring/assets/i18n/URL prefix. Final URL = ${prefix}${lang}${suffix}.
suffixstring.jsonURL suffix.
enforceLoadingbooleanfalseIf true, appends a cache-busting ?enforceLoading=<timestamp> query string to bypass HTTP caches.
useHttpBackendbooleanfalseIf true, bypasses HTTP interceptors by using HttpBackend directly.
failOnErrorbooleanfalseSee failOnError below.
flattenbooleanfalseNormalize nested objects to dotted keys before merging. See flatten.
onLoadError(failure: TranslateHttpLoaderError) => voidundefinedReports each failed resource attempt. See onLoadError below.

Pass resources instead of prefix/suffix to load and deep-merge several sources per language. Each entry can be a bare prefix string, or a { prefix, suffix } object. All resources are fetched in parallel; results are deep-merged in order, so later entries overwrite earlier entries on key collisions.

provideTranslateHttpLoader({
resources: [
'/assets/i18n/common/', // shared dictionary
{ prefix: '/assets/i18n/feature/', suffix: '.json' }, // feature overrides
],
})
NameTypeDefaultDescription
resources(string | { prefix: string; suffix?: string })[]requiredResources to load and merge per language. Later entries overwrite earlier on collision.
enforceLoadingbooleanfalseCache-busting query string, as above.
useHttpBackendbooleanfalseBypass interceptors via HttpBackend.
failOnErrorbooleanfalseSee failOnError below.
flattenbooleanfalseNormalize each resource before merging. See flatten.
onLoadError(failure: TranslateHttpLoaderError) => voidundefinedReports each failed resource attempt. See onLoadError below.

provideTranslateMultiHttpLoader() is also exported as an explicit alias of the multi-resource form.

This built-in support replaces the standalone @codeandweb/ngx-translate-multi-http-loader package.

Set flatten: true when shared translations and application overrides use different combinations of nested objects and flat, dotted keys. The loader flattens each resource before merging, so resource order determines which equivalent key wins. For example, a later {"menu.title": "Application"} overrides an earlier {"menu": {"title": "Library"}}.

/*
* AI GENERATED CODE: This snippet was produced or modified by AI. Review it carefully before relying on it.
* Model: GPT-6
* Prompt: Demonstrate opt-in flattening for shared and application translation files.
*/
provideTranslateHttpLoader({
resources: ['/assets/i18n/common/', '/assets/i18n/application/'],
flatten: true,
})

The default is false, preserving existing nested objects and lookup precedence. With flattening enabled, request individual dotted keys such as menu.title; the parent key menu no longer returns the original subtree. Arrays, including objects inside them, are kept intact. Null values, empty strings and empty objects are preserved. If one resource contains equivalent flat and nested keys, the last one encountered in JavaScript property enumeration order wins.

By default the HTTP loader is permissive (failOnError: false): a failed request (for example a 404 on a missing language file) is caught per-resource, replaced with an empty object, and logged via console.warn(@ngx-translate/http-loader: error loading translation for <lang>: ...) unless an onLoadError callback is configured. Other resources still contribute their keys, and the app keeps rendering with partial translations.

Pass failOnError: true to restore the v17 fail-fast behavior. Any per-resource failure then propagates and fails the whole language load. Use this when a missing translation file should fail a deploy rather than silently serve a partial dictionary.

provideTranslateHttpLoader({
prefix: '/assets/i18n/',
failOnError: true,
})

failOnError: true is also required when using the service’s retry option to retry HTTP failures.

Use onLoadError to report resource failures through your own logger or monitoring service. The option is available on both TranslateHttpLoaderConfig and TranslateMultiHttpLoaderConfig: it works with either form of provideTranslateHttpLoader() and with provideTranslateMultiHttpLoader().

import { provideTranslateService } from '@ngx-translate/core';
import {
provideTranslateHttpLoader,
type TranslateHttpLoaderError,
} from '@ngx-translate/http-loader';
provideTranslateService({
loader: provideTranslateHttpLoader({
resources: ['/assets/i18n/common/', '/assets/i18n/feature/'],
onLoadError: ({ lang, resource, url, error }: TranslateHttpLoaderError) => {
console.warn('Translation resource failed', { lang, resource, url, error });
},
}),
});

Replace the example’s console.warn with your application’s reporting call. The callback receives a TranslateHttpLoaderError, exported from @ngx-translate/http-loader:

FieldTypeDescription
langstringThe requested language, before URL encoding.
resourcestring | TranslateHttpLoaderResourceThe failing entry from resources. For the single-source form, this is a { prefix, suffix } object with defaults applied.
urlstring | undefinedThe constructed URL, including the encoded language and any enforceLoading query string. undefined if language encoding failed before URL construction.
errorunknownThe original error. Narrow its type before accessing properties such as an HTTP status.

The callback runs once for each failed resource attempt, including failures during service retries. Successful requests do not call it. It also reports failures before an HTTP request, such as malformed Unicode that cannot be encoded or rejected . and .. language values. A constructed url does not guarantee that a request was sent.

Reporting does not change the failure policy:

failOnErrorWith onLoadErrorWithout onLoadError
false (default)Call the callback, then substitute {} for the failed resource. Other resources still contribute their keys.Log the default loader warning, then substitute {}.
trueCall the callback, then propagate the original error and fail the whole language load.Propagate the original error without a loader warning.

Setting onLoadError alone does not enable retries. Configure both the service’s retry option and failOnError: true to retry HTTP failures. With multiple resources, each retry repeats the whole language load; the callback reports any resource that fails again.

The callback replaces only the loader’s default warning. Separate TranslateService warnings after a terminal loading failure still apply. If the callback throws synchronously, the loader warns that onLoadError failed and continues with the original loading outcome: {} in permissive mode or the original loading error in strict mode.

ImprintPrivacy