Skip to content

Commit

Permalink
Updated LocaleService & upgraded to beta.16
Browse files Browse the repository at this point in the history
  • Loading branch information
robisim74 committed Apr 26, 2016
1 parent 026c1be commit e37c6e2
Show file tree
Hide file tree
Showing 8 changed files with 352 additions and 192 deletions.
110 changes: 58 additions & 52 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
# Angular 2 Localization
> An Angular 2 library to translate messages, dates and numbers.
## Sample app
Sample application that implements the translation: [demo](http://robisim74.github.io/angular2localization)
Sample app that implements the translation: [demo](http://robisim74.github.io/angular2localization)

## Installation
You can add `angular2localization` to your project via [Node and npm](https://nodejs.org):
Expand All @@ -12,12 +11,10 @@ npm install --save angular2localization
To load the package you have two methods:
- Loading the bundle:
```Html
<!--loads angular2localization-->
<script src="node_modules/angular2localization/bundles/angular2localization.js"></script>
```
- Using SystemJS:
```Html
<!--configures SystemJS-->
<script>
System.config({
defaultJSExtensions: true,
Expand Down Expand Up @@ -50,40 +47,40 @@ import {TranslatePipe} from 'angular2localization/angular2localization';
```
With Angular 2 `I18nSelectPipe` that displays the string that matches the current value:
```Html
{{ gender | i18nSelect: inviteMapping | translate }}
{{ expression | i18nSelect:mapping | translate }}
```
With Angular 2 `I18nPluralPipe` that pluralizes the value properly:
```Html
{{ messages.length | i18nPlural: messageMapping | translate }}
{{ expression | i18nPlural:mapping | translate }}
```

### Dates
```
expression | localedate[:format]
```
where `expression` is a date object or a number (milliseconds since UTC epoch) and `format` indicates which date/time components to include. See Angular 2 `DatePipe` for further information.
where `expression` is a date object or a number (milliseconds since UTC epoch) and `format` indicates which date/time components to include.

For example, to get the local date, add in the template:
```Html
{{ today | localedate: 'fullDate' }}
{{ today | localedate:'fullDate' }}
```
and include `LocaleDatePipe` in the component.
and include `LocaleDatePipe` in the component. See Angular 2 `DatePipe` for further information.

### Numbers
#### Decimals
```
expression | number[:digitInfo]
expression | localedecimal[:digitInfo]
```
where `expression` is a number and `digitInfo` has the following format: `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`. See Angular 2 `DecimalPipe` for further information.
where `expression` is a number and `digitInfo` has the following format: `{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}`.

For example, to get the local decimal, add in the template:
```Html
{{ pi | localedecimal:'1.5-5' }}
```
and include `LocaleDecimalPipe` in the component.
and include `LocaleDecimalPipe` in the component. See Angular 2 `DecimalPipe` for further information.
#### Percentages
```
expression | percent[:digitInfo]
expression | localepercent[:digitInfo]
```

For example, to get the local percentage, add in the template:
Expand All @@ -93,7 +90,7 @@ For example, to get the local percentage, add in the template:
and include `LocalePercentPipe` in the component.
#### Currencies
```
expression | currency[:symbolDisplay[:digitInfo]]]
expression | localecurrency[:symbolDisplay[:digitInfo]]]
```
where `symbolDisplay` is a boolean indicating whether to use the currency symbol (e.g. $) or the currency code (e.g. USD) in the output.

Expand All @@ -106,32 +103,28 @@ and include `LocaleCurrencyPipe` in the component.
## First scenario
> You need to localize dates and numbers, but no messages.
### Basic usage
Add in the route component in order to access the data of location from anywhere in the application:
```TypeScript
// Services.
import {LocaleService} from 'angular2localization/angular2localization';

@Component({
selector: 'app-component',
...
providers: [LocaleService], // Inherited by all descendants.
})

export class AppComponent {

constructor(public locale: LocaleService,) {

// Initializes LocaleService.
this.locale.definePreferredLanguage('en'); // Required: default language (ISO 639 two-letter code).

// Default country for date & numbers (ISO 3166 two-letter, uppercase code).
this.locale.definePreferredCountry('US');

// Required: default language (ISO 639 two-letter code) and country (ISO 3166 two-letter, uppercase code).
this.locale.definePreferredLocale('en', 'US');

// Optional: default currency (ISO 4217 three-letter code).
this.locale.definePreferredCurrency('USD');

}

}
```

Expand All @@ -141,36 +134,35 @@ export class AppComponent {
### Basic usage
Add in the route component in order to access the data of location from anywhere in the application:
```TypeScript
// Services.
import {LocaleService} from 'angular2localization/angular2localization';
import {LocalizationService} from 'angular2localization/angular2localization';
import {LocaleService, LocalizationService} from 'angular2localization/angular2localization';

@Component({
selector: 'app-component',
...
providers: [LocaleService, LocalizationService], // Localization providers: inherited by all descendants.
providers: [LocaleService, LocalizationService], // Inherited by all descendants.
})

export class AppComponent {

constructor(public locale: LocaleService, public localization: LocalizationService) {

// Initializes LocaleService.
this.locale.addLanguage('en'); // Required: adds a new language (ISO 639 two-letter code).
this.locale.addLanguage('it');

// Adds a new language (ISO 639 two-letter code).
this.locale.addLanguage('en');
// Add a new language here.
this.locale.definePreferredLanguage('en', 30); // Required: default language and expiry (No days). If the expiry is omitted, the cookie becomes a session cookie.


// Required: default language and expiry (No days). If the expiry is omitted, the cookie becomes a session cookie.
this.locale.definePreferredLanguage('en', 30);

}

}
```
Also add in the main:
```TypeScript
bootstrap(AppComponent, [HTTP_PROVIDERS]);
```
#### Direct loading
To initialize `LocalizationService` for the direct loading, add the following code in the body of the constructor of the route component:
To initialize `LocalizationService` for the direct loading, add the following code in the body of constructor of the route component:
```TypeScript
var translationEN = {
TITLE: 'Angular 2 Localization',
Expand All @@ -179,13 +171,15 @@ var translationEN = {
}
// Add a new translation here.

this.localization.addTranslation('en', translationEN); // Required: adds a new translation with the given language code.
// Required: adds a new translation with the given language code.
this.localization.addTranslation('en', translationEN);
// Add a new translation with the given language code here.
```
#### Asynchronous loading
To initialize `LocalizationService` for the asynchronous loading add the following code in the body of the constructor of the route component:
Alternatively, to initialize `LocalizationService` for the asynchronous loading add the following code in the body of constructor of the route component:
```TypeScript
this.localization.translationProvider('./resources/locale-'); // Required: initializes the translation provider with the given path prefix.
// Required: initializes the translation provider with the given path prefix.
this.localization.translationProvider('./resources/locale-');
```
and create the `json` files of the translations such as `locale-en.json`:
```
Expand Down Expand Up @@ -214,7 +208,8 @@ export class I18nComponent {
// Instantiates a new LocalizationService for this component and for its descendants.
constructor(public localizationI18n: LocalizationService) {

this.localizationI18n.translationProvider('./resources/locale-i18n-'); // Required: initializes the translation provider with the given path prefix.
// Required: initializes the translation provider with the given path prefix.
this.localizationI18n.translationProvider('./resources/locale-i18n-');

}

Expand All @@ -233,19 +228,24 @@ where `language` is the two-letter code of the new language (ISO 639).
> You need to translate messages, dates and numbers.
### Basic usage
In addition to what has been said for the messages, add the following code in the body of the constructor of the route component:
Unlike what said for messages, use the following code in the body of the constructor of the route component:
```TypeScript
// Default country for date & numbers (ISO 3166 two-letter, uppercase code).
this.locale.definePreferredCountry('US');
// Adds a new language (ISO 639 two-letter code).
this.locale.addLanguage('en');
// Add a new language here.

// Required: default language, country (ISO 3166 two-letter, uppercase code) and expiry (No days). If the expiry is omitted, the cookie becomes a session cookie.
this.locale.definePreferredLocale('en', 'US', 30);

// Optional: default currency (ISO 4217 three-letter code).
this.locale.definePreferredCurrency('USD');
```
### Changing country and currency
To change country at runtime, call the following method:
### Changing locale and currency
To change locale at runtime, call the following method:
```TypeScript
this.locale.setCurrentCountry(country);
this.locale.setCurrentLocale(language, country);
```
where `country` is the two-letter, uppercase code of the new country (ISO 3166).
where `language` is the two-letter code of the new language (ISO 639) and `country` is the two-letter, uppercase code of the new country (ISO 3166).

To change currency at runtime, call the following method:
```TypeScript
Expand All @@ -256,7 +256,13 @@ where `currency` is the three-letter code of the new currency (ISO 4217).
See the [demo](http://robisim74.github.io/angular2localization) for a sample code.

## Internationalization API
To localize dates and numbers, this library uses Intl, through the classes available in Angular 2. For browsers compatibility, follow this [issue](https://github.com/angular/angular/issues/3333).
To localize dates and numbers, this library uses `Intl` API, through Angular 2.
All modern browsers, except Safari, have implemented this API. You can use [Intl.js](https://github.com/andyearnshaw/Intl.js) to extend support to all browsers.
Just add one script tag in your `index.html`:
```Html
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en-US"></script>
```
When specifying the `features`, you have to specify what locale, or locales to load.

##License
MIT
6 changes: 3 additions & 3 deletions gulpfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,14 +30,14 @@ var config = {
builder.config(config);

// Clean task: cleans the contents of the bundles directory.
gulp.task('clean', function() {
gulp.task('clean', function () {

return del(dest);

});

// Bundles task: creates bundles files.
gulp.task('bundles', ['clean'], function() {
// Bundles task: creates files.
gulp.task('bundles', ['clean'], function () {

// Creates js file.
builder.bundle('angular2localization/angular2localization', dest + '/angular2localization.js', { minify: false, sourceMaps: false });
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "angular2localization",
"version": "0.5.0",
"version": "0.5.1",
"description": "An Angular 2 library to translate messages, dates and numbers",
"main": "",
"scripts": {},
Expand All @@ -25,12 +25,12 @@
"homepage": "https://github.com/robisim74/angular2localization",
"typings": "./angular2localization.d.ts",
"dependencies": {
"angular2": "2.0.0-beta.15",
"angular2": "2.0.0-beta.16",
"systemjs": "0.19.26",
"es6-shim": "^0.35.0",
"reflect-metadata": "0.1.2",
"rxjs": "5.0.0-beta.2",
"zone.js": "0.6.10"
"zone.js": "0.6.12"
},
"devDependencies": {
"typescript": "^1.8.9",
Expand Down
31 changes: 15 additions & 16 deletions src/pipes/locale-date.pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {InvalidPipeArgumentException} from 'angular2/src/common/pipes/invalid_pi
import {LocaleService} from '../services/locale.service';

/**
* localedate pipe function.
* 'localedate' pipe function.
*/
@Pipe({
name: 'localedate',
Expand All @@ -25,28 +25,29 @@ import {LocaleService} from '../services/locale.service';

/**
* LocaleDatePipe class.
* An instance of this class is created for each localedate pipe function.
* An instance of this class is created for each 'localedate' pipe function.
*
* Getting the local date:
*
* expression | localedate[:format]
*
* where 'expression' is a date object or a number (milliseconds since UTC epoch) and 'format' indicates which date/time components to include.
*
* See DatePipe for further information.
*
* For example, to get the local date, add in the template:
*
* {{ today | localedate: 'fullDate' }}
* {{ today | localedate:'fullDate' }}
*
* and include LocaleDatePipe in the component:
*
* and in the component:
* import {LocaleDatePipe} from 'angular2localization/angular2localization';
*
* @Component({
* ...
* pipes: [LocaleDatePipe]
* })
*
* @author Roberto Simonetti
* @see Angular 2 DatePipe for further information
*/
@Injectable() export class LocaleDatePipe implements PipeTransform {
static ALIASES: { [key: string]: String } = {
Expand All @@ -61,12 +62,12 @@ import {LocaleService} from '../services/locale.service';
};

/**
* The default locale for the localedate pipe.
* The default locale for LocaleDatePipe.
*/
private defaultLocale: string;

/**
* The value of the localedate pipe.
* The value of LocaleDatePipe.
*/
private value: any;

Expand All @@ -78,13 +79,13 @@ import {LocaleService} from '../services/locale.service';
constructor(public locale: LocaleService) { }

/**
* Localedate pipe transform method.
* LocaleDatePipe transform method.
*
* @params value The date to be localized
* @params args The format of the date
* @param value The date to be localized
* @param pattern The format of the date
* @return The locale date
*/
transform(value: any, args: any[]): string {
transform(value: any, pattern: string = 'mediumDate'): string {

if (isBlank(value)) return null;

Expand All @@ -100,8 +101,6 @@ import {LocaleService} from '../services/locale.service';
// - the default locale has changed.
if (this.value != value || this.localeDate == "" || this.defaultLocale != this.locale.getDefaultLocale()) {

var pattern: string = isPresent(args) && args.length > 0 ? args[0] : 'mediumDate';

if (isNumber(value)) {

value = DateWrapper.fromMillis(value);
Expand All @@ -114,9 +113,9 @@ import {LocaleService} from '../services/locale.service';

}

// Updates the default locale for the localedate pipe.
// Updates the default locale for LocaleDatePipe.
this.defaultLocale = this.locale.getDefaultLocale();
// Updates the value of the localedate pipe.
// Updates the value of LocaleDatePipe.
this.value = value;

// Gets the locale date.
Expand Down
Loading

0 comments on commit e37c6e2

Please sign in to comment.