Skip to content

TranslateCompiler API

After translations are loaded by the TranslateLoader, they are passed through the TranslateCompiler. The compiler prepares each message for faster lookup at translate time. For example, ngx-translate-messageformat-compiler uses this API to compile ICU MessageFormat strings into interpolation functions.

The matching provider helper is provideTranslateCompiler(). See Configuration → Provider helpers.

export abstract class TranslateCompiler {
abstract compile(value: string, lang: string): InterpolatableTranslation;
abstract compileTranslations(
translations: TranslationObject,
lang: string,
): InterpolatableTranslationObject;
}
  • compile() compiles a single translation value.
  • compileTranslations() iterates over a full translation object, calling compile() on each value.

When a single message is requested, the TranslateParser consumes the compiler’s result. The default parser behaves differently depending on the result type:

  • string → standard {{placeholder}} substitution.
  • InterpolateFunction → called with the interpolation parameters; expected to return a string:
const compiledTranslations = {
hello: (params: any) => `Hello ${params.name}!`,
};

If you ship translations that are already in their final interpolator-ready form (e.g. emitted by a build step), store them with setCompiledTranslation() to bypass the compiler.

app.config.ts
import { provideTranslateService, provideTranslateCompiler } from '@ngx-translate/core';
export const appConfig: ApplicationConfig = {
providers: [
provideTranslateService({
compiler: provideTranslateCompiler(MyCompiler),
}),
],
};

The factory form is also supported:

provideTranslateService({
compiler: provideTranslateCompiler(() => new MyCompiler({ icu: true })),
})

For a step-by-step guide see Custom Translation Compilers.

Since v18.1, the default parser passes an optional second argument to compiled functions:

import type {
InterpolationContext,
InterpolationParameters,
} from '@ngx-translate/core';
export type InterpolateFunction = (
params?: InterpolationParameters,
context?: InterpolationContext,
) => string;

context.key is the requested translation key. context.lang is the language that supplied the message, including fallback and parent-service lookups. See Interpolation context for cases where context is unavailable and for object or array translations.

Existing functions that accept only params continue to work. The compiler’s lang argument is unchanged and is still available at compile time. Context is supplied when a function is interpolated, including functions stored through setCompiledTranslation(). A custom parser must forward context to the function to support this behavior.

ImprintPrivacy