Translations in Angular 2

A common requirement in Angular 2 is configure and share a service used from all the components of the application.

In a multilanguage application, a service that we need to use is the provider for the language translations; obviously this module will be used in all the components, or at least in those that have an html template.

The service that we use is ng2-translate; what we need to do is installing the package, provide it with a shared module and use the translation service in the components.

Installation

First we install the package:

npm install ng2-translate –save

Once installed, we have to configure the package with a module loader like SystemJS (or Webpack):

(function (global) {
System.config({
paths: {
'npm:': 'node_modules/'
},
map: {
app: 'app',
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
.....
'ng2-translate': 'npm:ng2-translate/bundles/index.js'
},
packages: {
.....
}
});
})(this);

Now the package is installed and configured and we can going to provide the service.

Providing

As explained below, in order to provide the service we have to use a shared module of the application; we already have discussed in a previous post a module like that, and we can edit it:

import { NgModule, ModuleWithProviders, Optional, SkipSelf } from "@angular/core";
.....
import { TranslateModule } from "ng2-translate";
.....
@NgModule ({
imports: [
.....
],
exports: [
.....
TranslateModule,
.....
]
})
export class SharedModule {}

We have to export the TraslateModule in order to make it shared; otherwise the others modules won’t be able to use it.

Now the translate module is provided and we can define the translations; by using the default configuration, we can create the i18n folder in the root of the project and create a json file for every language supported.

For example, en.json:

{
"NEW": "New",
"SAVE": "Save",
"CLOSE": "Close",
"DELETE": "Delete",
"NAME": "Name",
"ADDRESS": "Address",
"ATTACHMENT": "Attachment",
"ATTACHINVOICE": "Attach invoice",
"CITY": "City",
"ZIP": "Zip",
"DISTRICT": "District",
"COUNTRY": "Country",
"NUMBER": "Number",
"YEAR": "Year",
"CUSTOMER": "Customer",
"EMISSIONDATE": "Emission Date",
"DUEDATE": "Due Date",
"PAYMENTDATE": "Payment Date",
"CUSTOMERSLOADED": "Customers loaded successfully",
"CUSTOMERSAVED": "Customer saved",
"CUSTOMERDELETED": "Customer deleted",
"SEARCH": "Search",
"INVOICESLOADED": "Invoices loaded successfully",
"INVOICESAVED": "Invoice saved",
"INVOICEDELETED": "Invoice deleted"
}

Now we are ready to use the translations in the components of the application.

Translations

The service that make the work of translation is the TranslateService, and we import it:

import { Component, OnInit } from "@angular/core";
import { TranslateService } from "ng2-translate";
.....
@Component({
moduleId: module.id,
selector: "customer",
templateUrl: "customer.component.html"
})
export class CustomerComponent implements OnInit {
constructor(private customerService: CustomerService, private alertService: AlertService, private searchService: SearchService, <strong>private translateService: TranslateService</strong>) {}
public Load() {
this.alertService.isLoading = true;
this.customerService.GetAll().subscribe(
(data) => {
this.alertService.isLoading = false;
this.customers = data;
this.customer = null;
this.translateService.get("CUSTOMERSLOADED").subscribe((res: string) => {
this.alertService.Success(res);
});
},
(error) => this.alertService.Error(error));
}
.....
}

In this code, we inject the service in the component constructor and we use it to translate the CUSTOMERLOADED resource and show an alert message.

Another purpose of the translation service is translate the labels of a view:

<div [hidden]="edit">
<input type="button" class="btn btn-primary" value="New" (click)="New()" />
<table class="table table-striped">
<thead>
<tr>
<th>
{{ "NAME" | translate }}</th>
<th>
{{ "ADDRESS" | translate }}</th>
<th>
{{ "CITY" | translate }}</th>
</tr>
</thead>
<tbody>
.....</tbody>
</table>
</div>
.....

Here you can find the github repository with the source code.

 

One thought on “Translations in Angular 2

Add yours

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: