Internazionalizzazione in Angular con ngx-translate
In questo articolo vediamo come usare ngx-translate per tradurre le nostre applicazioni Angular.
Dovremmo installare due moduli:
npm install @ngx-translate/core @ngx-translate/http-loader
Il secondo ci servirà per recuperare le lingue dal server; in verità le metteremo tutte dentro alla cartella assets.
Una volta installate modifichiamo il nostro app.module.ts:
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {TranslateLoader, TranslateModule} from '@ngx-translate/core';
import {AppComponent} from './app.component';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
import {HttpClient, HttpClientModule} from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
},
defaultLanguage: 'it'
})
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
export function HttpLoaderFactory(http: HttpClient): TranslateHttpLoader {
return new TranslateHttpLoader(http);
}
Nel nostro component:
import {Component} from '@angular/core';
import {TranslateService} from '@ngx-translate/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private translate: TranslateService) {
// translate.setDefaultLang('it');
// translate.use('it');
}
cambiaLingua(language: string): void {
this.translate.use(language);
}
}
Come vedete ci sono due righe commentate; a noi non servono perchè abbiamo impostato già l'italiano come lingua predefinita nell'app.module.ts.
Il nostro HTML sarà una cosa del genere:
<div>
<h1>{{ 'test.titolo' | translate }}</h1>
<p>{{ 'test.testo' | translate }}</p>
<p [translate]="'test.testo'"></p>
<p translate>test.testo</p>
</div>
<hr>
<button (click)="cambiaLingua('it')">it</button>
<button (click)="cambiaLingua('en')">en</button>
Qui vi ho mostrato tutti i vari modi in cui è possibile richiamare le lingue.
L'ultimo passaggio da fare è creare due files dentro assets/i18n; questo i it.json:
{
"test": {
"titolo": "Titolo in italiano",
"testo": "Questa è una frase in italiano"
}
}
E questo en.json:
{
"test": {
"titolo": "English title",
"testo": "Here we are!"
}
}
Enjoy!
javascript typescript angular internazionalizzazione ngx-translate json
Commentami!