We are using Angular 6 in our Application. In that application we want to give multilingual support.
How can we implement localisation & Internationalization in angular 6? Its an angular 6 version.
We are using Angular 6 in our Application. In that application we want to give multilingual support.
How can we implement localisation & Internationalization in angular 6? Its an angular 6 version.
Refer: https://dgwebidea.blogspot.com/2020/01/angular-internationalization-and.html
Translate Angular 6 apps with ngx-translate What we will do:
Create minimal Angular6 project Install and load ngx-translate Init the TranslateService Create .json translation files Translate simple title and intro Integrate language switcher Translate sentence with variable
Create minimal Angular6 project
We use @angular/cli to create a new project named “traduction” in the terminal:
ng new traduction --prefix tr
cd traduction
ng serve -o
Install and load ngx-translate
Use npm in your terminal within the project folder “traduction”:
npm install @ngx-translate/core --save
npm install @ngx-translate/http-loader
Note: Use following versions forbelow angular 6
"@ngx-translate/core": "^9.1.1"
"@ngx-translate/http-loader": "^3.0.1"
and for angular 5 use latest version 10 and above
Import the necessary modules into app.module.ts :
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
Add a function, that returns a “TranslateHttpLoader” and export it (needed by AoT). In this case the HttpLoaderFactory function we create, returns a Object that can load Translations using Http and .json, but you could write your own Class that for example uses a global JavaScript variable instead of loading a file, or that uses Google Translate:
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
OR
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http, 'assets/i18n/', '.json');
}
We then need to import our modules into the @NgModule, this is the import that tells Angular to load this Module into your AppModule:
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [],
bootstrap: [AppComponent]
})
Inject the TranslateService
In “app.component.ts” we now init the “TranslateService”, we import the TranslateService:
import { TranslateService } from '@ngx-translate/core';
Then inside the AppComponent Class we inject the service and define our default language. And to be ready for the next step, we add a function to switch the language.
constructor(private translate: TranslateService) {
translate.setDefaultLang('en');
}
switchLanguage(language: string) {
this.translate.use(language);
}
Create .json translation files
We now create our translation files inside the assets/i18n folder:
src/assets/i18n/en.json
{
"Title": "Translation example",
"Intro": "Hello I am Arthur, I am 42 years old."
}
src/assets/i18n/fr.json
{
"Title": "Exemple de traduction",
"Intro": "Bonjour je m'appelle Arthur, j'ai 42 ans."
}
These are simple .json files that will be loaded by our “TranslateHttpLoader” we created in “app.module.ts”.
Translate simple title and intro
In app.component.html we add a header with the translate “directive” inside the “h1” tag. This directive will take the text inside the tag and replace it with the matching translation. If you use the directive you have to make sure, that there is nothing else inside the tag but the text.
As a second example we use the “TranslationPipe” to translate a label with define as a inline string. As we sometimes have value inside a translation that we want to replace, we can pass a data object into the “translate” pipe.
<h1 translate>Title</h1>
<div>
{{ 'Intro' | translate:user }}
</div>
Integrate language switcher
We can now attach our language switcher function that we saw above in app.component.ts to a button. In this case we create a button for each language and call the switchLanguage() function with the matching language key.
<button (click)="switchLanguage('en')">en</button>
<button (click)="switchLanguage('fr')">fr</button>
Translate sentence with variable
As mentioned before, you sometimes have sentences to that contain variable. In this little example we have a user object with age and name inside the “app.component.ts”, and we want to translate a sentence that will contain this values:
...
export class AppComponent {
user = {
name: 'Arthur',
age: 42
};
...
}
Because we pass this object into the “translate” pipe, we can now use it’s properties in our translation with the {{ placeholder }} notation.
src/assets/i18n/en.json
{
"Title": "Translation example",
"Intro": "Hello I am {{name}}, I am {{age}} years old."
}
src/assets/i18n/fr.json
{
"Title": "Exemple de traduction",
"Intro": "Bonjour je m'appelle {{name}}, j'ai {{age}} ans."
}
Using nested .json objects
If you want to be able to have more control on your translation, and for example translate page blocks (from the end-user perspective) or components (from the developer perspective), one solution could be the following; use nested .json objects as described in the git repo. An example could look like this in the -json files:
{
"Title": "Translation example",
"Intro": "Hello I am {{name}}, I am {{age}} years old.",
"Startpage": {
"TranslationSections": "Hello World"
},
"Aboutpage": {
"TranslationSections": "We are letsboot"
}
}
{
"Title": "Exemple de traduction",
"Intro": "Bonjour je m'appelle {{name}}, j'ai {{age}} ans.",
"Startpage": {
"TranslationSections": "Bonjour Monde"
},
"Aboutpage": {
"TranslationSections": "Nous sommes letsboot"
}
}
And in the corresponding template:
<h1 translate>Title</h1>
<div>
{{ 'Intro' | translate:user }}
</div>
<div>
{{ 'Startpage.TranslationSections' | translate }}
</div>
<div>
{{ 'Aboutpage.TranslationSections' | translate }}
</div>
<br/>
<button (click)="switchLanguage('en')">en</button>
<button (click)="switchLanguage('fr')">fr</button>
"@ngx-translate/core": "9.1.1", "@ngx-translate/http-loader": "2.0.1",
–
Nickolai "@angular/core": "5.2.2"
not 6 –
Nickolai Error: StaticInjectorError(AppModule)[rootTextManager -> TranslateService]: StaticInjectorError(Platform: core)[rootTextManager -> TranslateService]: NullInjectorError: No provider for TranslateService!
–
Nickolai RootTextManager
into appmodule's providers. Still getting same error –
Nickolai component.module.ts
export function translateHttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: translateHttpLoaderFactory,
deps: [HttpClient]
}
})
class LanguagService.ts
import { Injectable } from '@angular/core';
import { TranslateService, LangChangeEvent } from '@ngx-translate/core';
import { ReplaySubject } from 'rxjs';
import { take } from 'rxjs/operators';
@Injectable({ providedIn: 'root' })
export class LanguageService {
language$ = new ReplaySubject<LangChangeEvent>(1);
translate = this.translateService;
// 國旗對照;
constructor(private translateService: TranslateService) {}
setInitState() {
this.translateService.addLangs(['en', 'cn','vi']);
console.log( 'Browser Lang', this.translate.getBrowserLang());
const browserLang = (this.translate.getBrowserLang().includes('vi')) ? 'vi' : 'cn' ;
console.log("anhtt "," anguage = " +browserLang);
this.setLang(browserLang);
}
setLang(lang: string) {
this.translateService.onLangChange.pipe(take(1)).subscribe(result => {
this.language$.next(result);
});
this.translateService.use(lang);
}
}
app.component.html
<h1>How to multi language in angular 7</h1>
<p >{{'content' |translate}}</p>
<h4 translate>
{{'message' |translate}}
</h4>
<button (click)="selectLanguageEN()">English</button>
<button (click)="selectLanguageCN()">中國</button>
<button (click)="selectLanguageVI()">Viet Nam</button>
Code demo:
https://tienanhvn.blogspot.com/2019/06/angular-7-how-to-multi-language.html
© 2022 - 2024 — McMap. All rights reserved.