Try Live
Add Docs
Rankings
Pricing
Docs
Install
Theme
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Ngx-Translate
https://github.com/ngx-translate/core
Admin
The internationalization (i18n) library for Angular, providing tools and features to translate
...
Tokens:
10,282
Snippets:
33
Trust Score:
5.8
Update:
4 months ago
Context
Skills
Chat
Benchmark
94.5
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# @ngx-translate/core ## Introduction @ngx-translate/core is the internationalization (i18n) library for Angular applications, supporting versions 16-20. It provides a comprehensive solution for managing multiple languages in Angular apps with dynamic language switching, translation loading, parameter interpolation, and fallback language support. The library integrates seamlessly with Angular's dependency injection system and provides both imperative (service-based) and declarative (pipe/directive-based) APIs for translating content. The project consists of two main packages: `@ngx-translate/core` which provides the core translation functionality including the TranslateService, pipes, directives, and extensible architecture for custom loaders, compilers, and parsers; and `@ngx-translate/http-loader` which enables loading translation files from a server via HTTP. The library supports advanced features like nested translation keys, interpolation parameters, observable streams for reactive updates, browser language detection, and custom handlers for missing translations. ## APIs and Key Functions ### Module Setup with TranslateModule.forRoot() Sets up the translation service in your root Angular module with configuration for loaders, compilers, parsers, and initial language settings. ```typescript import { ApplicationConfig } from '@angular/core'; import { provideHttpClient } from '@angular/common/http'; import { TranslateModule, TranslateLoader } from '@ngx-translate/core'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { HttpClient } from '@angular/common/http'; import { importProvidersFrom } from '@angular/core'; // Factory function for creating the loader export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(http, './assets/i18n/', '.json'); } export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(), importProvidersFrom( TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient] }, fallbackLang: 'en', lang: 'en' }) ) ] }; ``` ### Standalone Component Setup with provideTranslateService() Modern standalone API for configuring translations without NgModules, using Angular's new functional providers approach. ```typescript import { ApplicationConfig } from '@angular/core'; import { provideHttpClient } from '@angular/common/http'; import { provideTranslateService, TranslateLoader } from '@ngx-translate/core'; import { provideTranslateHttpLoader } from '@ngx-translate/http-loader'; export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(), provideTranslateService({ loader: provideTranslateHttpLoader({ prefix: './assets/i18n/', suffix: '.json' }), fallbackLang: 'en', lang: 'en' }) ] }; ``` ### TranslateService.use() Switches the active language and loads translations if not already loaded, returning an observable that completes when translations are ready. ```typescript import { Component, inject, OnInit } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'app-language-switcher', template: ` <select (change)="switchLanguage($event)"> <option value="en">English</option> <option value="es">Español</option> <option value="fr">Français</option> <option value="de">Deutsch</option> </select> <p>{{ 'CURRENT_LANG' | translate }}: {{ currentLang }}</p> ` }) export class LanguageSwitcherComponent implements OnInit { private translate = inject(TranslateService); currentLang: string = ''; ngOnInit() { // Set initial language this.translate.use('en').subscribe({ next: (translations) => { this.currentLang = this.translate.getCurrentLang(); console.log('Translations loaded:', translations); }, error: (err) => { console.error('Failed to load translations:', err); } }); } switchLanguage(event: Event) { const lang = (event.target as HTMLSelectElement).value; this.translate.use(lang).subscribe(() => { this.currentLang = this.translate.getCurrentLang(); }); } } ``` ### TranslateService.get() Retrieves translated values for single or multiple keys, returning an observable that resolves with the translation or an object of translations. ```typescript import { Component, inject, OnInit } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'app-welcome', template: ` <div> <h1>{{ welcomeMessage }}</h1> <p>{{ description }}</p> <button (click)="loadGreeting()">Load Greeting</button> </div> ` }) export class WelcomeComponent implements OnInit { private translate = inject(TranslateService); welcomeMessage: string = ''; description: string = ''; ngOnInit() { // Get single translation this.translate.get('WELCOME.TITLE').subscribe((text: string) => { this.welcomeMessage = text; }); // Get multiple translations at once this.translate.get(['WELCOME.TITLE', 'WELCOME.DESCRIPTION', 'WELCOME.SUBTITLE']) .subscribe((translations: any) => { console.log(translations); // Output: { 'WELCOME.TITLE': '...', 'WELCOME.DESCRIPTION': '...', ... } this.welcomeMessage = translations['WELCOME.TITLE']; this.description = translations['WELCOME.DESCRIPTION']; }); } loadGreeting() { // Get translation with interpolation parameters this.translate.get('GREETING', { name: 'John', time: 'evening' }) .subscribe((text: string) => { // Translation file: "GREETING": "Good {{time}}, {{name}}!" // Result: "Good evening, John!" console.log(text); }); } } ``` ### TranslateService.instant() Synchronously retrieves translations from already-loaded translation data without waiting for observables, useful for non-async contexts. ```typescript import { Component, inject } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { Router } from '@angular/router'; @Component({ selector: 'app-confirm-dialog', template: ` <div class="dialog"> <h2>{{ title }}</h2> <p>{{ message }}</p> <button (click)="confirm()">{{ confirmText }}</button> <button (click)="cancel()">{{ cancelText }}</button> </div> ` }) export class ConfirmDialogComponent { private translate = inject(TranslateService); private router = inject(Router); // Use instant() for synchronous access when translations are already loaded title = this.translate.instant('DIALOG.CONFIRM_TITLE'); message = this.translate.instant('DIALOG.CONFIRM_MESSAGE'); confirmText = this.translate.instant('DIALOG.CONFIRM_BUTTON'); cancelText = this.translate.instant('DIALOG.CANCEL_BUTTON'); confirm() { // Using instant() with parameters const successMsg = this.translate.instant('DIALOG.SUCCESS', { action: 'saved', count: 5 }); alert(successMsg); // "Successfully saved 5 items" // Using instant() with array of keys const messages = this.translate.instant(['DIALOG.SUCCESS', 'DIALOG.ERROR']); console.log(messages); // { 'DIALOG.SUCCESS': '...', 'DIALOG.ERROR': '...' } } cancel() { this.router.navigate(['/']); } } ``` ### TranslateService.stream() Returns an observable stream of translations that automatically updates whenever the language changes, perfect for reactive UI components. ```typescript import { Component, inject, OnInit } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { Observable } from 'rxjs'; @Component({ selector: 'app-live-translation', template: ` <div> <h1>{{ title$ | async }}</h1> <p>{{ description$ | async }}</p> <p>{{ greeting$ | async }}</p> <button (click)="switchToEnglish()">English</button> <button (click)="switchToSpanish()">Español</button> </div> ` }) export class LiveTranslationComponent implements OnInit { private translate = inject(TranslateService); title$!: Observable<string>; description$!: Observable<string>; greeting$!: Observable<string>; username = 'Alice'; ngOnInit() { // Stream updates automatically when language changes this.title$ = this.translate.stream('PAGE.TITLE'); this.description$ = this.translate.stream('PAGE.DESCRIPTION'); // Stream with interpolation parameters this.greeting$ = this.translate.stream('PAGE.GREETING', { name: this.username }); // Can also subscribe directly this.translate.stream('PAGE.FOOTER').subscribe((text: string) => { console.log('Footer text updated to:', text); }); } switchToEnglish() { this.translate.use('en'); // All streams automatically emit new translations } switchToSpanish() { this.translate.use('es'); // All streams automatically emit new translations } } ``` ### TranslatePipe (translate pipe) Angular pipe for declarative translation in templates with automatic updates when language or translation data changes. ```typescript import { Component, inject } from '@angular/core'; import { TranslateService, TranslatePipe } from '@ngx-translate/core'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-product-details', standalone: true, imports: [CommonModule, TranslatePipe], template: ` <div class="product"> <!-- Simple translation --> <h1>{{ 'PRODUCT.TITLE' | translate }}</h1> <!-- Translation with parameters (object syntax) --> <p>{{ 'PRODUCT.PRICE' | translate: {amount: 29.99, currency: 'USD'} }}</p> <!-- Translation file: "PRODUCT.PRICE": "Price: {{amount}} {{currency}}" --> <!-- Result: "Price: 29.99 USD" --> <!-- Translation with parameters (string syntax - will be parsed) --> <p>{{ 'PRODUCT.STOCK' | translate: '{count: 15, status: "available"}' }}</p> <!-- Nested translation key --> <span>{{ 'PRODUCT.CATEGORY.ELECTRONICS' | translate }}</span> <!-- Dynamic translation key --> <p>{{ currentKey | translate }}</p> <!-- Translation with multiple parameters --> <div class="description"> {{ 'PRODUCT.DESCRIPTION' | translate: { name: productName, brand: productBrand, year: 2024 } }} </div> <button (click)="changeLanguage()"> {{ 'BUTTON.SWITCH_LANG' | translate }} </button> </div> ` }) export class ProductDetailsComponent { private translate = inject(TranslateService); productName = 'Laptop Pro'; productBrand = 'TechCorp'; currentKey = 'PRODUCT.WARRANTY'; changeLanguage() { const currentLang = this.translate.getCurrentLang(); const newLang = currentLang === 'en' ? 'es' : 'en'; this.translate.use(newLang); // Pipe automatically updates all translations } } ``` ### TranslateDirective Directive for translating element content using attributes, supporting both content-based and key-based translation with parameter interpolation. ```typescript import { Component, inject } from '@angular/core'; import { TranslateService, TranslateDirective } from '@ngx-translate/core'; import { CommonModule } from '@angular/common'; @Component({ selector: 'app-user-profile', standalone: true, imports: [CommonModule, TranslateDirective], template: ` <div class="profile"> <!-- Using translate attribute with key --> <h1 [translate]="'USER.PROFILE_TITLE'"></h1> <!-- Using translate directive with parameters --> <p [translate]="'USER.WELCOME_MESSAGE'" [translateParams]="{username: currentUser, lastLogin: lastLoginDate}"> </p> <!-- Translation file: "USER.WELCOME_MESSAGE": "Welcome back, {{username}}! Last login: {{lastLogin}}" --> <!-- Using content as translation key --> <span translate>USER.STATUS</span> <!-- Alternative ngx-translate syntax --> <div ngx-translate="USER.BIO" [translateParams]="{age: userAge, city: userCity}"> </div> <!-- Translate with dynamic key --> <p [translate]="dynamicKey" [translateParams]="dynamicParams"> </p> <div class="actions"> <button (click)="updateLanguage('en')">English</button> <button (click)="updateLanguage('fr')">Français</button> </div> </div> ` }) export class UserProfileComponent { private translate = inject(TranslateService); currentUser = 'JohnDoe'; lastLoginDate = '2024-01-15'; userAge = 28; userCity = 'Paris'; dynamicKey = 'USER.SETTINGS'; dynamicParams = { theme: 'dark', notifications: 'enabled' }; updateLanguage(lang: string) { this.translate.use(lang); // Directive automatically updates translations } } ``` ### TranslateService.setTranslation() Manually sets translation objects for a language, useful for dynamic translations or setting translations without loading from files. ```typescript import { Component, inject, OnInit } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'app-dynamic-translations', template: ` <div> <h1>{{ 'DYNAMIC.TITLE' | translate }}</h1> <p>{{ 'DYNAMIC.MESSAGE' | translate }}</p> <button (click)="loadCustomTranslations()">Load Custom</button> <button (click)="mergeTranslations()">Merge Additional</button> </div> ` }) export class DynamicTranslationsComponent implements OnInit { private translate = inject(TranslateService); ngOnInit() { // Set translations manually without a loader this.translate.setTranslation('en', { DYNAMIC: { TITLE: 'Dynamic Translations', MESSAGE: 'These translations were set programmatically' } }); // Set translations for another language this.translate.setTranslation('es', { DYNAMIC: { TITLE: 'Traducciones Dinámicas', MESSAGE: 'Estas traducciones se establecieron programáticamente' } }); this.translate.use('en'); } loadCustomTranslations() { // Replace existing translations this.translate.setTranslation('en', { DYNAMIC: { TITLE: 'Updated Title', MESSAGE: 'This is a completely new translation set', NEW_KEY: 'This key was just added' } }, false); // false = replace, don't merge } mergeTranslations() { // Merge with existing translations (third parameter = true) this.translate.setTranslation('en', { DYNAMIC: { ADDITIONAL: 'This is merged with existing translations', EXTRA_INFO: 'Original keys are preserved' } }, true); // true = merge with existing } } ``` ### TranslateService.setFallbackLang() and getFallbackLang() Configures and retrieves the fallback language used when translations are missing in the current language. ```typescript import { Component, inject, OnInit } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'app-fallback-demo', template: ` <div> <p>Current Lang: {{ currentLang }}</p> <p>Fallback Lang: {{ fallbackLang }}</p> <p>{{ 'COMMON.GREETING' | translate }}</p> <p>{{ 'COMMON.MISSING_KEY' | translate }}</p> </div> ` }) export class FallbackDemoComponent implements OnInit { private translate = inject(TranslateService); currentLang: string = ''; fallbackLang: string | null = ''; ngOnInit() { // Set English as fallback language this.translate.setFallbackLang('en').subscribe({ next: () => { console.log('Fallback language loaded'); this.fallbackLang = this.translate.getFallbackLang(); }, error: (err) => { console.error('Failed to load fallback language:', err); } }); // If a key doesn't exist in 'es', it will fall back to 'en' this.translate.use('es').subscribe(() => { this.currentLang = this.translate.getCurrentLang(); }); // Check current fallback language console.log('Current fallback:', this.translate.getFallbackLang()); } } ``` ### TranslateHttpLoader with provideTranslateHttpLoader() Loads translation files from HTTP endpoints with configurable paths, supports multiple resource loading and cache busting. ```typescript import { ApplicationConfig } from '@angular/core'; import { provideHttpClient } from '@angular/common/http'; import { provideTranslateService } from '@ngx-translate/core'; import { provideTranslateHttpLoader } from '@ngx-translate/http-loader'; // Basic configuration export const appConfig: ApplicationConfig = { providers: [ provideHttpClient(), provideTranslateService({ loader: provideTranslateHttpLoader({ prefix: './assets/i18n/', suffix: '.json' }), // Translations loaded from: ./assets/i18n/en.json, ./assets/i18n/es.json, etc. fallbackLang: 'en' }) ] }; // Advanced: Multiple translation sources export const advancedConfig: ApplicationConfig = { providers: [ provideHttpClient(), provideTranslateService({ loader: provideTranslateHttpLoader({ resources: [ { prefix: './assets/i18n/common/', suffix: '.json' }, { prefix: './assets/i18n/features/', suffix: '.json' }, './assets/i18n/overrides/' ], enforceLoading: false, // Set true to add cache-busting timestamp showLog: true, // Enable error logging useHttpBackend: false // Set true to bypass HTTP interceptors }), fallbackLang: 'en' }) ] }; // Example translation files structure: // ./assets/i18n/common/en.json // ./assets/i18n/common/es.json // ./assets/i18n/features/en.json // ./assets/i18n/features/es.json // Common translations (./assets/i18n/common/en.json): /* { "COMMON": { "WELCOME": "Welcome", "GOODBYE": "Goodbye" } } */ // Feature translations (./assets/i18n/features/en.json): /* { "FEATURES": { "DASHBOARD": "Dashboard", "SETTINGS": "Settings" } } */ ``` ### TranslateService Browser Language Detection Static methods to detect the user's browser language settings for automatic language initialization. ```typescript import { Component, inject, OnInit } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'app-auto-language', template: ` <div> <p>Detected Browser Language: {{ browserLang }}</p> <p>Detected Browser Culture: {{ browserCulture }}</p> <p>Current Language: {{ currentLang }}</p> <p>{{ 'APP.TITLE' | translate }}</p> </div> ` }) export class AutoLanguageComponent implements OnInit { private translate = inject(TranslateService); browserLang: string = ''; browserCulture: string = ''; currentLang: string = ''; ngOnInit() { // Add available languages this.translate.addLangs(['en', 'es', 'fr', 'de', 'it']); this.translate.setFallbackLang('en'); // Get browser language (e.g., "en" from "en-US") this.browserLang = this.translate.getBrowserLang() || 'en'; // Get full culture code (e.g., "en-US") this.browserCulture = this.translate.getBrowserCultureLang() || 'en-US'; // Use browser language if it's supported, otherwise fallback const langToUse = this.translate.getLangs().includes(this.browserLang) ? this.browserLang : 'en'; this.translate.use(langToUse).subscribe(() => { this.currentLang = this.translate.getCurrentLang(); console.log(`Using language: ${this.currentLang}`); }); // Alternative: Use static method const staticBrowserLang = TranslateService.getBrowserLang(); const staticBrowserCulture = TranslateService.getBrowserCultureLang(); console.log('Static detection:', staticBrowserLang, staticBrowserCulture); } } ``` ### TranslateService Event Observables Subscribe to language and translation change events for reactive handling of translation updates. ```typescript import { Component, inject, OnDestroy, OnInit } from '@angular/core'; import { TranslateService, LangChangeEvent, TranslationChangeEvent } from '@ngx-translate/core'; import { Subscription } from 'rxjs'; @Component({ selector: 'app-translation-events', template: ` <div> <h2>Translation Event Monitor</h2> <div class="events"> <p *ngFor="let event of events">{{ event }}</p> </div> <button (click)="switchLanguage('es')">Switch to Spanish</button> <button (click)="switchLanguage('fr')">Switch to French</button> <button (click)="updateTranslations()">Update Translations</button> </div> ` }) export class TranslationEventsComponent implements OnInit, OnDestroy { private translate = inject(TranslateService); events: string[] = []; private subscriptions = new Subscription(); ngOnInit() { // Listen to language changes this.subscriptions.add( this.translate.onLangChange.subscribe((event: LangChangeEvent) => { this.events.push(`Language changed to: ${event.lang}`); console.log('Lang changed:', event.lang); console.log('New translations:', event.translations); }) ); // Listen to translation changes (when translations are updated for current lang) this.subscriptions.add( this.translate.onTranslationChange.subscribe((event: TranslationChangeEvent) => { this.events.push(`Translations updated for: ${event.lang}`); console.log('Translations changed for:', event.lang); console.log('Updated translations:', event.translations); }) ); // Listen to fallback language changes this.subscriptions.add( this.translate.onFallbackLangChange.subscribe((event) => { this.events.push(`Fallback language changed to: ${event.lang}`); console.log('Fallback lang changed:', event); }) ); this.translate.setFallbackLang('en'); this.translate.use('en'); } switchLanguage(lang: string) { this.translate.use(lang); } updateTranslations() { // Manually update translations - triggers onTranslationChange this.translate.setTranslation(this.translate.getCurrentLang(), { NEW_KEY: 'New translation added dynamically' }, true); } ngOnDestroy() { this.subscriptions.unsubscribe(); } } ``` ### Custom TranslateLoader Implementation Create custom loaders for loading translations from any source (API, local storage, database, etc.). ```typescript import { Injectable } from '@angular/core'; import { TranslateLoader, TranslationObject } from '@ngx-translate/core'; import { Observable, of } from 'rxjs'; import { delay } from 'rxjs/operators'; // Custom loader from in-memory data @Injectable() export class CustomTranslateLoader implements TranslateLoader { private translations: Record<string, TranslationObject> = { en: { CUSTOM: { TITLE: 'Custom Loader', MESSAGE: 'Loaded from custom source' } }, es: { CUSTOM: { TITLE: 'Cargador Personalizado', MESSAGE: 'Cargado desde fuente personalizada' } } }; getTranslation(lang: string): Observable<TranslationObject> { console.log(`Loading translations for ${lang} from custom loader`); // Simulate async loading return of(this.translations[lang] || {}).pipe(delay(100)); } } // Custom loader from API @Injectable() export class ApiTranslateLoader implements TranslateLoader { constructor(private http: HttpClient) {} getTranslation(lang: string): Observable<TranslationObject> { // Load from custom API endpoint return this.http.get<TranslationObject>(`https://api.example.com/translations/${lang}`); } } // Custom loader from localStorage with fallback @Injectable() export class StorageTranslateLoader implements TranslateLoader { constructor(private http: HttpClient) {} getTranslation(lang: string): Observable<TranslationObject> { // Try localStorage first const cached = localStorage.getItem(`translations_${lang}`); if (cached) { console.log(`Loading ${lang} from localStorage cache`); return of(JSON.parse(cached)); } // Fallback to HTTP console.log(`Loading ${lang} from server`); return this.http.get<TranslationObject>(`./assets/i18n/${lang}.json`) .pipe( tap(translations => { // Cache in localStorage localStorage.setItem(`translations_${lang}`, JSON.stringify(translations)); }), catchError(error => { console.error(`Failed to load ${lang}:`, error); return of({}); }) ); } } // Usage in configuration import { ApplicationConfig } from '@angular/core'; import { provideTranslateService, TranslateLoader } from '@ngx-translate/core'; export const appConfig: ApplicationConfig = { providers: [ provideTranslateService({ loader: { provide: TranslateLoader, useClass: CustomTranslateLoader }, fallbackLang: 'en' }) ] }; ``` ### Custom MissingTranslationHandler Implement custom behavior when translations are missing, such as logging, fallbacks, or API requests. ```typescript import { Injectable } from '@angular/core'; import { MissingTranslationHandler, MissingTranslationHandlerParams } from '@ngx-translate/core'; import { Observable, of } from 'rxjs'; @Injectable() export class CustomMissingTranslationHandler implements MissingTranslationHandler { handle(params: MissingTranslationHandlerParams): string { console.warn(`Missing translation for key: ${params.key}`); console.warn(`Current language: ${params.translateService.getCurrentLang()}`); if (params.interpolateParams) { console.warn(`Parameters:`, params.interpolateParams); } // Return a custom formatted missing translation return `[MISSING: ${params.key}]`; } } // Advanced handler with API fallback @Injectable() export class ApiFallbackMissingTranslationHandler implements MissingTranslationHandler { constructor(private http: HttpClient) {} handle(params: MissingTranslationHandlerParams): Observable<string> { const { key, translateService, interpolateParams } = params; const lang = translateService.getCurrentLang(); console.warn(`Translation missing for ${key} in ${lang}, fetching from API...`); // Try to fetch from API return this.http.get<{translation: string}>( `https://api.example.com/translate?key=${key}&lang=${lang}` ).pipe( map(response => response.translation), catchError(() => { // If API fails, return the key with parameters return of(`[${key}]`); }) ); } } // Usage in configuration import { ApplicationConfig } from '@angular/core'; import { provideTranslateService, provideMissingTranslationHandler } from '@ngx-translate/core'; export const appConfig: ApplicationConfig = { providers: [ provideTranslateService({ missingTranslationHandler: provideMissingTranslationHandler( CustomMissingTranslationHandler ), fallbackLang: 'en' }) ] }; ``` ### Custom TranslateParser for Custom Interpolation Syntax Create custom parsers to support different interpolation syntaxes beyond the default `{{ }}` pattern. ```typescript import { Injectable } from '@angular/core'; import { TranslateParser, InterpolationParameters } from '@ngx-translate/core'; @Injectable() export class CustomTranslateParser extends TranslateParser { // Custom template matcher for ${variable} syntax templateMatcher = /\$\{([^}]+)\}/g; interpolate(expr: string | Function, params?: InterpolationParameters): string | undefined { if (typeof expr === 'string') { return this.interpolateString(expr, params); } else if (typeof expr === 'function') { return expr(params); } return undefined; } private interpolateString(expr: string, params?: InterpolationParameters): string { if (!params) { return expr; } return expr.replace(this.templateMatcher, (substring: string, key: string) => { const value = params[key.trim()]; return value !== undefined ? String(value) : substring; }); } } // Parser with advanced formatting @Injectable() export class AdvancedTranslateParser extends TranslateParser { templateMatcher = /{{\s?([^{}\s]*)\s?}}/g; interpolate(expr: string | Function, params?: InterpolationParameters): string | undefined { if (typeof expr === 'function') { return expr(params); } if (typeof expr === 'string') { return this.interpolateWithFormatting(expr, params); } return undefined; } private interpolateWithFormatting(expr: string, params?: InterpolationParameters): string { if (!params) return expr; return expr.replace(this.templateMatcher, (substring: string, key: string) => { const [varName, format] = key.split(':').map(s => s.trim()); const value = params[varName]; if (value === undefined) return substring; // Apply formatting if specified if (format === 'upper') return String(value).toUpperCase(); if (format === 'lower') return String(value).toLowerCase(); if (format === 'capitalize') { return String(value).charAt(0).toUpperCase() + String(value).slice(1); } return String(value); }); } } // Usage in configuration import { ApplicationConfig } from '@angular/core'; import { provideTranslateService, provideTranslateParser } from '@ngx-translate/core'; export const appConfig: ApplicationConfig = { providers: [ provideTranslateService({ parser: provideTranslateParser(CustomTranslateParser), fallbackLang: 'en' }) ] }; // Example usage with custom parser: // Translation file: { "GREETING": "Hello, ${name}! You have ${count} messages." } // Component: translate.get('GREETING', { name: 'John', count: 5 }) // Result: "Hello, John! You have 5 messages." // With advanced parser: // Translation file: { "USER": "Welcome {{ name:upper }}" } // Result: "Welcome JOHN" ``` ## Summary @ngx-translate/core provides a robust, extensible internationalization solution for Angular applications with support for multiple languages, dynamic translation loading, and seamless integration with Angular's reactive programming model. The library's core strength lies in its flexible architecture that allows developers to use translations declaratively through pipes and directives in templates, or imperatively through the TranslateService in components. The observable-based API ensures that translations update reactively when languages change, while the instant() method provides synchronous access for non-reactive contexts. The library's main use cases include multi-language web applications requiring dynamic language switching, applications needing to load translations from various sources (HTTP, APIs, local storage), and projects requiring custom translation logic through extensible loaders, parsers, compilers, and missing translation handlers. Integration patterns typically involve setting up the translation module at the application root with a loader (commonly the HTTP loader for JSON files), configuring fallback languages for graceful degradation, and using a combination of pipes for template translations and service methods for programmatic translations. Advanced use cases include implementing custom loaders for specialized translation sources, creating custom parsers for alternative interpolation syntax, and building missing translation handlers that log errors or fetch translations from external services on-demand.