git clone https://github.com/Manoranjan-D/Angular-Internationalization.git
cd Angular-Internationalization && npm i
npm start
Navigate to http://localhost:4200/
. The app will automatically reload if you change any of the source files.
docker pull manoranjandocker/angular-internationalization
docker run -d --rm -p 8080:80 manoranjandocker/angular-internationalization
Navigate to http://localhost:8080/
.
-
Create angular project
ng new project-name
-
Install Dependency
npm install @npx-translate/core @npx-translate/http-loader
-
Create internationalization folder (i18n) in your project & create language json files inside i18n folder
-
Export a function in app module
export function createTranslateLoader(http: HttpClient) {
return new TranslateHttpLoader(http, "./assets/i18n/", ".json");
}
- Initiate the translate module and set the default language
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpClientModule,
FormsModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: createTranslateLoader,
deps: [HttpClient],
},
defaultLanguage: 'en',
}),
],
providers: [],
bootstrap: [AppComponent],
})
- Create service to change the language
export class TranslationService {
constructor(private translateService: TranslateService) {}
public changeLanguage(type: string) {
this.translateService.use(type);
}
}
- Can access the i18n json files in our html template and use the pipe operator | to enable translation
<p>{{ "Demo-app.title" | translate }}</p>
- By injecting the translate service in .ts file, can change the language based on the used action
export class AppComponent {
constructor(private trnaslationService: TranslationService) {}
onChangeLnguage(type: string) {
this.trnaslationService.changeLanguage(type);
}
}