Locale L10N
This plugin provides localization(l10n) support for Transloco.
Localization refers to the adaptation of a product, application or document content to meet the language, cultural and other requirements of a specific target market (a locale).
Installation
npm i @jsverse/transloco-locale
- Standalone
- NgModule
Setup
Add the locale providers to your app config:
export const appConfig = {
providers: [
provideTranslocoLocale(),
...
]
};
Import the TranslocoLocaleModule
or the directive/pipe you are using into your standalone component.
Export the TranslocoLocaleModule
along with TranslocoModule
from the TranslocoRootModule
and add the locale providers:
import { TranslocoLocaleModule, provideTranslocoLocale } from '@jsverse/transloco-locale';
@NgModule({
exports: [ TranslocoModule, TranslocoLocaleModule ],
providers: [
provideTranslocoLocale()
...
],
})
export class TranslocoRootModule {}
Localization Pipes
The library provides localization API provided by pipes or from a service, base on the native Javascript's API.
Date Pipe
Transform a date into the locale's date format.
The date expression could be: a Date object, a number (milliseconds since UTC epoch), or an ISO string.
<!--9/10/2019-->
<span> {{ date | translocoDate }} </span>
<!-- Sep 10, 2019, 10:46:12 PM-->
<span>
{{ date | translocoDate: { dateStyle: 'medium', timeStyle: 'medium' } }}
</span>
<!-- 7:40:32 PM Coordinated-->
<span>
{{ date | translocoDate: { timeZone: 'UTC', timeStyle: 'full' } }}
</span>
<!-- Jan 1, 1970-->
<span> {{ 1 | translocoDate: { dateStyle: 'medium' } }} </span>
<!-- Feb 8, 2019-->
<span> {{ '2019-02-08' | translocoDate: { dateStyle: 'medium' } }} </span>
Currency Pipe
Transform a given number into the locale's currency format.
The library comes out of the box with locale currency mapping, so once the locale is change the currency will automatically display the right currency.
The currency mapping could be customise if needed through the config, and could be provided by provideTranslocoLocaleCurrencyMapping
.
<!--$1,000,000.00-->
<span> {{ 1000000 | translocoCurrency }} </span>
<!--1,000,000.00 US dollars-->
<span> {{ 1000000 | translocoCurrency: 'name' }} </span>
<!--$1,000,000-->
<span>
{{ 1000000 | translocoCurrency: 'symbol' : { minimumFractionDigits: 0 } }}
</span>
Decimal Pipe
Transform a given number into current locale's decimal number format.
<!--1,234,567,890-->
<span> {{ 1234567890 | translocoDecimal }} </span>
<!--1234567890-->
<span> {{ 1234567890 | translocoDecimal: {useGrouping: false} }} </span>
Percent Pipe
Transform a given number into current locale's percent number format.
<!--100%-->
<span> 1 | translocoPercent </span>
<!--100%-->
<span> "1" | translocoPercent </span>
Setting Locale
The library provides three different ways to set the locale.
Translation file names
Using locale format for the translation files will automatically declare the locale on langChanges$
event:
├─ i18n/
├─ en-US.json
├─ en-GB.json
├─ es-ES.json
Language Locale Mapping:
Users who don't have more than one locale per language
could provide a language to locale mapping object using the config's langToLocaleMapping
:
export const appConfig = {
providers: [
provideTranslocoLocale({
langToLocaleMapping: {
en: 'en-US',
es: 'es-ES'
}
})
...
]
};
import { TranslocoLocaleModule, provideTranslocoLocale } from '@jsverse/transloco-locale';
@NgModule({
exports: [ TranslocoModule, TranslocoLocaleModule ],
providers: [
provideTranslocoLocale({
langToLocaleMapping: {
en: 'en-US',
es: 'es-ES'
}
})
...
],
})
export class TranslocoRootModule {}
Manually Setting Locale:
The third option in manually setting the locale, this could be done by calling setLocale
method from localeService
:
export class AppComponent {
constructor(private service: TranslocoLocaleService) {}
ngOnInit() {
this.service.setLocale('en-US');
}
}
Configuration Options
Let's go over each one of the config
options:
localeConfig?
: Declare the default configuration of the locale's formatting. A general configuration could be set using theglobal
property, for a configuration by locale uselocaleBased
property (default value determine by the native Javascript's API).defaultLocale?
: The default locale formatted in BCP 47 (default value:en-US
),langToLocaleMapping?
: A key valueobject
that maps Transloco language to it's Locale (default value:{}
).localeToCurrencyMapping?
: A key valueobject
that maps the Locale to its currency (formatted in ISO 4217) (the library provide a default value with all of the existing mapping).
Locale Format Options
There are two types of formatting options, one for date
and one for number
.
The formatted options could be declared in three levels
- In the app's configuration (as mentioned above):
const globalFormatConfig = {
date: {
dateStyle: 'long',
timeStyle: 'long'
}
};
const esESFormatConfig = {
date: {
timeStyle: 'medium'
},
currency: {
minimumFractionDigits: 0
}
};
export const appConfig = {
providers: [
provideTranslocoLocale({
localeConfig: {
global: globalFormatConfig,
localeBased: {
'es-ES': esESFormatConfig
}
}
})
...
]
};
- In the module's configuration (as mentioned above):
import { TranslocoLocaleModule } from '@jsverse/transloco-locale';
const globalFormatConfig = {
date: {
dateStyle: 'long',
timeStyle: 'long'
}
};
const esESFormatConfig = {
date: {
timeStyle: 'medium'
},
currency: {
minimumFractionDigits: 0
}
};
@NgModule({
exports: [ TranslocoModule, TranslocoLocaleModule ],
providers: [
provideTranslocoLocale({
localeConfig: {
global: globalFormatConfig,
localeBased: {
'es-ES': esESFormatConfig
}
}
})
...
],
})
export class TranslocoRootModule {}
- It could be set in the component's providers using
provideTranslocoLocaleConfig
:
@Component({
selector: 'my-comp',
templateUrl: './my-comp.component.html',
providers: [provideTranslocoLocaleConfig(localeConfig)],
})
export class MyComponent {}
- We can pass it to each pipe in the HTML template:
<span>
{{ date | translocoDate: { dateStyle: 'medium', timeStyle: 'medium' } }}
</span>
<span> {{ number | translocoDecimal: {useGrouping: false} }} </span>
Note the format option of the global, locale's format and the one's being passed in the template, will be merged. While the template is the stronger one and then the locale and the global.
Number Format Options
useGrouping
- Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators. Possible values are true and false; the (default is true).minimumIntegerDigits
- The minimum number of integer digits to use. Possible values are from 1 to 21 (default is 1).minimumFractionDigits
- The minimum number of fraction digits to use. Possible values are from 0 to 20 (default is 0).maximumFractionDigits
- The maximum number of fraction digits to use. Possible values are from 0 to 20 (default is 3).minimumSignificantDigits
- The minimum number of significant digits to use. Possible values are from 1 to 21 (default is 1).maximumSignificantDigits
- The maximum number of significant digits to use. Possible values are from 1 to 21 (default is 21).currency
- The currency to use in currency formatting. Possible values are the ISO 4217 currency codes, such as "USD" for the US dollar, "EUR" for the euro.signDisplay
- When to display the sign for the number. Possible values are "auto", "always", "exceptZero", "negative", "never" (default is "auto").
Date Format Options
dateStyle
- The date formatting style.timeStyle
- The time formatting style.timeZone
- The time zone to use. The only value implementations must recognize is "UTC"; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the IANA time zone database, such as "Asia/Shanghai", "Asia/Kolkata", "America/New_York".
By default those options are passed to the native Intl.DateTimeFormat
, full documentation for the options you can find here
Service API
localeChanges$
- Observable of the active locale.localizeDate()
- Transform a date into a locale's date format.localizeNumber()
- Transform a number into the locale's number format according to the number type.getLocale
- Gets the active locale.setLocale
- Sets the active locale.getCurrencySymbol
- Gets the currency symbol for a given locale. If no locale is specified the currently active one is used.
translocoLocaleService.localeChanges$.subscribe(activeLocale => ...)
translocoLocaleService.localizeNumber(1234567890, 'decimal') // 1,234,567,890
translocoLocaleService.localizeNumber(0.5, 'percent') // 50%
translocoLocaleService.localizeNumber(1000, 'currency') // $1,000.00
const locale = translocoLocaleService.getLocale();
translocoLocaleService.setLocale('en-US')
translocoLocaleService.getCurrencySymbol() // $
Localization Transformer
In some cases you might want to customize the localization transformation, to achieve that you could provide your own localization transformer class.
There are two types of transformers for date and number:
import { DefaultDateTransformer, DefaultNumberTransformer } from '@jsverse/transloco-locale';
export class CustomDateTransformer extends DefaultDateTransformer {
public transform(date: Date, locale: Locale, options: DateFormatOptions): string {
return ...
// Fallback to default transformer
return super.transform(date, locale, options);
}
}
export class CustomNumberTransformer extends DefaultNumberTransformer {
public transform(
value: number | string,
type: NumberTypes,
locale: string,
options: Intl.NumberFormatOptions
): string {
return ...
// Fallback to default transformer
return super.transform(value, type, locale, options);
}
}
Provide these custom transformers using the provideTranslocoDateTransformer
and provideTranslocoNumberTransformer
functions.