Translation
Introduction
Egret Angular uses the ngx-translate
library to provide internationalization (i18n) support. This allows you to create a multilingual application where users can switch between different languages. This documentation will guide you through the implementation and usage of translations in your Egret Angular application.
Setup and Configuration
Egret Angular comes with translation support already configured. The translation module is set up in the app.module.ts
file:
// app.module.ts
import { HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
// AoT requires an exported function for factories
export function HttpLoaderFactory(httpClient: HttpClient) {
return new TranslateHttpLoader(httpClient);
}
@NgModule({
// ...
imports: [
// ...
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
}),
// ...
],
// ...
})
export class AppModule { }
The HttpLoaderFactory
function creates a loader that will fetch translation files from the assets/i18n
directory. By default, Egret Angular includes English (en) and Spanish (es) translations.
Translation Files
Translation files are JSON files located in the src/assets/i18n
directory. Each language has its own file with the language code as the filename (e.g., en.json
, es.json
).
Example: English Translation File (en.json)
{
"DASHBOARD": "Dashboard",
"APPS": "Apps",
"INBOX": "Inbox",
"CHAT": "Chat",
"CALENDAR": "Calendar",
"DIALOGS": "Dialogs",
"CONFIRM": "Confirm",
"LOADER": "Loader",
// ...
}
Example: Spanish Translation File (es.json)
{
"DASHBOARD": "Tablero",
"APPS": "Apps",
"INBOX": "Mensaje",
"CHAT": "Charla",
"CALENDAR": "Calendario",
"DIALOGS": "Diálogo",
"CONFIRM": "Confirmar",
"LOADER": "Loader",
// ...
}
Each key in the translation file corresponds to a translatable text in your application. The keys are typically in uppercase to distinguish them from regular text.
Using Translations in Templates
To use translations in your templates, you need to use the translate
pipe provided by the ngx-translate
library.
Basic Usage
<span>{{ "DASHBOARD" | translate }}</span>
This will display "Dashboard" if the current language is English or "Tablero" if the current language is Spanish.
Using in Navigation Items
In Egret Angular, navigation items are typically defined with translation keys:
<a matRipple routerLink="/{{item.state}}" *ngIf="item.type === 'link'">
<mat-icon>{{item.icon}}</mat-icon>
{{item.name | translate}}
</a>
Using in Breadcrumbs
When defining routes with breadcrumbs, you can use translation keys:
{
path: 'dialogs',
loadChildren: './views/app-dialogs/app-dialogs.module#AppDialogsModule',
data: { title: 'Dialogs', breadcrumb: 'DIALOGS' }
}
The breadcrumb component will automatically translate the 'DIALOGS' key to the appropriate language.
Using Translations in Components
To use translations in your TypeScript code, you need to inject the TranslateService
into your component.
import { Component, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.html'
})
export class MyComponent implements OnInit {
constructor(private translate: TranslateService) {}
ngOnInit() {
// Get a translation
this.translate.get('DASHBOARD').subscribe((res: string) => {
console.log(res); // Outputs: "Dashboard" or "Tablero" depending on the current language
});
// Get multiple translations at once
this.translate.get(['DASHBOARD', 'APPS']).subscribe((res: any) => {
console.log(res.DASHBOARD); // Outputs: "Dashboard" or "Tablero"
console.log(res.APPS); // Outputs: "Apps" or "Apps"
});
}
}
Language Switching
Egret Angular provides a language switcher in the header components. The implementation can be found in the header-side.component.ts
and header-top.component.ts
files.
Language Configuration
// In header components
public availableLangs = [{
name: 'EN',
code: 'en',
flag: 'us'
}, {
name: 'ES',
code: 'es',
flag: 'es'
}];
currentLang = this.availableLangs[0];
Setting the Default Language
ngOnInit() {
// ...
this.translate.use(this.currentLang.code);
}
Changing the Language
setLang(lng) {
this.currentLang = lng;
this.translate.use(lng.code);
}
Language Switcher in Template
<!-- Language Switcher -->
<button mat-button [matMenuTriggerFor]="menu">
<span class="fi fi-{{currentLang.flag}} mr-2 rtl:ml-2"></span>
<span>{{currentLang.name}}</span>
</button>
<mat-menu #menu="matMenu">
<button mat-menu-item *ngFor="let lang of availableLangs" (click)="setLang(lang)">
<span class="fi mr-2 rtl:ml-2 fi-{{lang.flag}}"></span>
<span>{{lang.name}}</span>
</button>
</mat-menu>
Adding New Languages
To add a new language to your Egret Angular application, follow these steps:
Step 1: Create a New Translation File
Create a new JSON file in the src/assets/i18n
directory with the language code as the filename (e.g., fr.json
for French).
// fr.json
{
"DASHBOARD": "Tableau de bord",
"APPS": "Applications",
"INBOX": "Boîte de réception",
"CHAT": "Chat",
"CALENDAR": "Calendrier",
// ... Add translations for all keys
}
Step 2: Update Available Languages
Update the availableLangs
array in the header components:
public availableLangs = [{
name: 'EN',
code: 'en',
flag: 'us'
}, {
name: 'ES',
code: 'es',
flag: 'es'
}, {
name: 'FR',
code: 'fr',
flag: 'fr'
}];
Step 3: Ensure All Keys are Translated
Make sure that all translation keys used in your application are present in the new translation file. Missing keys will fall back to the default language.
Translation Parameters
For dynamic content, you can use parameters in your translations:
Defining Parameterized Translations
// en.json
{
"WELCOME": "Welcome, {{name}}!"
}
Using Parameters in Templates
<span>{{ "WELCOME" | translate:{ name: userName } }}</span>
Using Parameters in Components
this.translate.get('WELCOME', { name: this.userName }).subscribe((res: string) => {
console.log(res); // Outputs: "Welcome, John!" (if userName is "John")
});
Best Practices
Follow these best practices to effectively use translations in your Egret Angular application:
Translation Guidelines
- Use uppercase keys for translation strings (e.g.,
DASHBOARD
,SETTINGS
). - Keep translation keys consistent across your application.
- Use consistent capitalization in your translations (all caps for keys that need translation).
- Consider using nested objects for complex translations or translations with parameters.
- Ensure all user-facing text is translatable, including error messages, tooltips, and button labels.
- Test your application with all supported languages to ensure proper display and layout.
Additional Resources
For more information on using ngx-translate, refer to the official documentation: