Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

angular-l10n

> 前端框架
Open source

Angular library to translate texts, dates and numbers

375 stars0 likes2 views
WebsiteGitHub

About

Angular library to translate texts, dates and numbers

Angular l10n

Angular library to translate texts, dates and numbers

This library is for localization of Angular apps. It allows, in addition to translation, to format dates and numbers through Internationalization API

Table of Contents

  • Installation
  • Usage
  • Lazy loading
  • Localized routing
  • Server Side Rendering
  • Types
  • Contributing
  • Versions

Installation

bash
npm install angular-l10n --save 

Usage

  • Sample standalone app
  • Sample SSR app
  • Live example on StackBlitz

Configuration

Create the configuration:

src/app/l10n-config.ts

…

The implementation of L10nTranslationLoader class-interface above creates a js chunk for each translation file in the src/i18n/[language]/[asset].json folder during the build:

src/i18n/en-US/app.json

json
{
  "home": {
    "greeting": "Hello world!",
    "whoIAm": "I am {{name}}",
    "devs": {
      "one": "One software developer",
      "other": "{{value}} software developers"
    }
  }
}

Note. The implementation above of L10nTranslationLoader is just an example: you can load the translation data in the way you prefer.

Register the configuration:

src/app/app.config.ts

typescript
export const appConfig: ApplicationConfig = {
  providers: [
    provideL10nTranslation(
      l10nConfig,
      {
        translationLoader: TranslationLoader
      }
    ),
    provideL10nIntl()
  ]
};

or with modules:

src/app/app.module.ts

typescript
@NgModule({
  imports: [
    L10nTranslationModule.forRoot(
      l10nConfig,
      {
        translationLoader: TranslationLoader
      }
    ),
    L10nIntlModule
  ]
})
export class AppModule { }

Getting the translation

Pure Pipes

xml

{{ 'home.greeting' | translate:locale.language }}

{{ 'home.whoIAm' | translate:locale.language:{ name: 'Angular l10n' } }}

{{ 2 | l10nPlural:locale.language:'home.devs' }}

{{ today | l10nDate:locale.language:{ dateStyle: 'full', timeStyle: 'short' } }}

{{ -1 | l10nTimeAgo:locale.language:'second':{ numeric:'always', style:'long' } }}

{{ 1000 | l10nNumber:locale.language:{ digits: '1.2-2', style: 'currency' } }}

{{ 'en-US' | l10nDisplayNames:locale.language:{ type: 'language' } }}

Pure pipes need to know when the locale changes. So import L10nLocale injection token in every component that uses them:

typescript
@Component({
  standalone: true,
  imports: [
    L10nTranslatePipe
  ]
})
export class PipeComponent {
  locale = inject(L10N_LOCALE);
}

or with modules:

typescript
export class PipeComponent {
    locale = inject(L10N_LOCALE);
}

OnPush Change Detection Strategy

To support this strategy, there is an Async version of each pipe, which recognizes by itself when the locale changes:

xml

{{ 'greeting' | translateAsync }}

Directives

Directives manipulate the DOM

xml

home.greeting

home.greeting

home.whoIAm

2

APIs

L10nTranslationService provides:

  • setLocale(locale: L10nLocale): Promise Changes the current locale and load the translation data
  • onChange(): Observable Fired every time the translation data has been loaded. Returns the locale
  • onError(): Observable Fired when the translation data could not been loaded. Returns the error
  • translate(keys: string | string[], params?: any, language?: string): string | any Translates a key or an array of keys

Changing the locale

You can change the locale at runtime at any time by calling the setLocale method of L10nTranslationService:

xml

  {{ item.locale.language | l10nDisplayNames:locale.language:{ type: 'language' } }}
typescript
export class AppComponent {

  schema = this.config.schema;

  constructor(
    @Inject(L10N_LOCALE) public locale: L10nLocale,
    @Inject(L10N_CONFIG) private config: L10nConfig,
    private translation: L10nTranslationService
  ) { }

  setLocale(locale: L10nLocale): void {
    this.translation.setLocale(locale);
  }
}

Class-interfaces

The following features can be customized. You just have to implement the indicated class-interface and pass the token during configuration.

Translation Loader

By default, you can only pass JavaScript objects as translation data provider. To implement a different loader, you can implement the L10nTranslationLoader class-interface, as in the example above.

typescript
export declare abstract class L10nTranslationLoader {
  /**
    * This method must contain the logic to get translation data.
    * @param language The current language
    * @param provider The provider of the translations data
    * @return An object of translation data for the language: {key: value}
    */
  abstract get(language: string, provider: L10nProvider): Observable;
}

Locale resolver

By default, the library attempts to set the locale using the user's browser language, before falling back to the default locale. You can change this behavior by implementing the L10nLocaleResolver class-interface, for example to get the language from the URL.

typescript
export declare abstract class L10nLocaleResolver {
  /**
   * This method must contain the logic to get the locale.
   * @return The locale
   */
  abstract get(): Promise;
}

Storage

By default, the library does not store the locale. To store it implement the L10nStorage class-interface using what you need, such as web storage or cookie, so that the next time the user has the locale he selected.

typescript
export declare abstract class L10nStorage {
  /**
   * This method must contain the logic to read the storage.
   * @return A promise with the value of the locale
   */
  abstract read(): Promise;
  /**
   * This method must contain the logic to write the storage.
   * @param locale The current locale
   */
  abstract write(locale: L10nLocale): Promise;
}

Missing Translation Handler

If a key is not found, the same key is returned. To return a different value, you can implement the L10nMissingTranslationHandler class-interface.

typescript
export declare abstract class L10nMissingTranslationHandler {
  /**
   * This method must contain the logic to handle missing values.
   * @param key The key that has been requested
   * @param value Null or empty string
   * @param params Optional parameters contained in the key
   * @return The value
   */
  abstract handle(key: string, value?: string, params?: any): string | any;
}

Translation fallback

If you enable translation fallback in configuration, the translation data will be merged in the following order:

  • 'language'
  • 'language[-script]'
  • 'language[-script][-region]'

To change it, implement the L10nTranslationFallback class-interface.

typescript
export declare abstract class L10nTranslationFallback {
  /**
   * This method must contain the logic to get the ordered loaders.
   * @param language The current language
   * @param provider The provider of the translations data
   * @return An array of loaders
   */
  abstract get(language: string, provider: L10nProvider): Observable[];
}

E.g.:

…

Loader

If you need to preload some data before initialization of the library, you can implement the L10nLoader class-interface.

typescript
export declare abstract class L10nTranslationLoader {
  /**
   * This method must contain the logic to get translation data.
   * @param language The current language
   * @param provider The provider of the translations data
   * @return An object of translation data for the language: {key: value}
   */
  abstract get(language: string, provider: L10nProvider): Observable;
}

E.g.:

typescript
@Injectable() export class AppLoader implements L10nLoader {
  constructor(private translation: L10nTranslationService) { }

  public async init(): Promise {
      await ... // Some custom data loading action
      await this.translation.init();
  }
}

Validation

There are two directives, that you can use with Template driven or Reactive forms: l10nValidateNumber and l10nValidateDate. To use them, you have to implement the L10nValidation class-interface, and import it with the L10nValidationModule module.

…

Lazy loading

If you want to add new providers to a lazy loaded component or module, you can use resolveL10n function in your routes:

typescript
const routes: Routes = [
  {
    path: 'lazy',
    loadComponent: () => import('./lazy/lazy.component').then(m => m.LazyComponent),
    resolve: { l10n: resolveL10n },
    data: {
      l10nProviders: [{ name: 'lazy', asset: 'lazy' }]
    }
  }
];

Or to lazy load a module:

typescript
const routes: Routes = [
  {
    path: 'lazy',
    loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule),
    resolve: { l10n: resolveL10n },
    data: {
      l10nProviders: [{ name: 'lazy', asset: 'lazy' }]
    }
  }
];

and import the modules you need:

typescript
@NgModule({
  declarations: [LazyComponent],
  imports: [
      L10nTranslationModule
  ]
})
export class LazyModule { }

Localized routing

Let's assume that we want to create a navigation of this type:

  • default language (en-US): routes not localized http://localhost:4200/home
  • other languages (it-IT): localized routes http://localhost:4200/it-IT/home

In routes root level add :lang param to create localizedRoutes:

typescript
const routes: Routes = [
  { path: 'home', component: HomeComponent },
  {
    path: 'lazy',
    loadChildren: () => import('./lazy/lazy.module').then(m => m.LazyModule),
    resolve: { l10n: resolveL10n },
    data: {
      l10nProviders: [{ name: 'lazy', asset: 'lazy' }]
    }
  }
];

export const localizedRoutes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  ...routes,
  {
    path: ':lang', // prepend [lang] to all routes
    children: routes
  },
  { path: '**', redirectTo: 'home' }
];

and provide it to the router.

Now let's implement the L10nLocaleResolver class-interface to get the language from the URL:

src/app/l10n-config.ts

typescript
@Injectable() export class LocaleResolver implements L10nLocaleResolver {

  constructor(@Inject(L10N_CONFIG) private config: L10nConfig, private location: Location) { }

  public async get(): Promise {
    const path = this.location.path();

    for (const schema of this.config.schema) {
      const language = schema.locale.language;
      if (new RegExp(`(\/${language}\/)|(\/${language}$)|(\/(${language})(?=\\?))`).test(path)) {
        return Promise.resolve(schema.locale);
      }
    }
    return Promise.resolve(null);
  }
}

and add it to configuration using provideL10nTranslation or L10nTranslationModule with modules.

When the app starts, the library will call the get method of LocaleResolver and use the locale of the URL or the default locale.

Do not implement storage when using the localized router, because the language of the URL may be inconsistent with the saved one

To change language at runtime, we can't use the setLocale method, but we have to navigate to the localized URL without reloading the page. We replace the setLocale method with the new navigateByLocale and we add pathLang to router links:

xml
Home
Lazy

  {{ item.locale.language | l10nDisplayNames:locale.language:{ type: 'language' } }}
…

Here we are doing three things:

  • we update pathLang provided to router links every time the locale changes
  • we implement navigateByLocale method, which takes care of replacing the language and navigating to the new URL
  • we ha

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptangularlocalizationtranslatetypescript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架