GithubHelp home page GithubHelp logo

navpreet2289 / angular-i18n-ngx-translate Goto Github PK

View Code? Open in Web Editor NEW

This project forked from cassilup/angular-i18n-ngx-translate

0.0 2.0 0.0 97 KB

An example of i18n in Angular using @ngx-translate

TypeScript 76.45% JavaScript 18.00% HTML 4.82% CSS 0.73%

angular-i18n-ngx-translate's Introduction

i18n in Angular Tutorial

i18n in Angular using ngx-translate Tutorial

Table of Contents

  1. Choosing a i18n strategy
  2. Install angular-cli
  3. Bootstrap the Angular App
  4. Serve the App in the Browser
  5. Create a New Component
  6. Install @ngx-translate
  7. Declare @ngx-translate in the App's Parent Module
  8. Automatically Extract Texts Marked for Translation
  9. Add ngx-translate-extract as a npm Script
  10. Inject translate Into the Main App Component
  11. Mark Texts for Translation
  12. Switch Languages
  13. Enjoy! ๐Ÿ˜Ž

1. Choosing a i18n strategy

The official Angular i18n solution is Enterprise-oriented and built to work with the industry standard translation source file format.

Traditionally, SPA apps use .json files for storing/loading reading locale data. @ngx-translate provides an accessible way of achieving that purpose.

Reasons I chose @ngx-translate over the official Angular i18n solution:

  1. The official Angular i18n solution forces you to build and deploy a separate version of the application for each supported language.
  2. @ngx-translate offers a HTTP Loader.
  3. @ngx-translate offers a string extractor tool that crawls all project source files and extracts texts marked for translation. In my opinion, this considerabily eases the locale files mainteinance.

Note:

@ngx-translate loads the .json files dynamically (during runtime) on a per-need basis. This means that when the app first loads, only the default locale file is downloaded. (This means that new locale files will be requested only when the language is changed.)

2. Install angular-cli

npm i -g @angular/cli

Note:

npm i -g is syntactic sugar for npm install --global.

3. Bootstrap the Angular App

ng new i18nExample
cd i18nExample

4. Serve the App in the Browser

ng s

Note:

ng s is syntactic sugar for ng serve.

5. Create a New Component

ng generate component sayHi

6. Install @ngx-translate

npm i -s @ngx-translate/core @ngx-translate/http-loader

Note:

npm i -s is syntactic sugar for npm install --save.

7. Declare @ngx-translate in the App's Parent Module

// app.module.ts

import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClientModule, HttpClient } from '@angular/common/http';

// ...

export const createTranslateLoader = (http: HttpClient) => {
  return new TranslateHttpLoader(http, './assets/i18n/', '.json');
};

// ...

imports: [
  // ...
  HttpClientModule,
  TranslateModule.forRoot({
    loader: {
      provide: TranslateLoader,
      useFactory: createTranslateLoader,
      deps: [HttpClient]
    }
  })
]

8. Automatically Extract Texts Marked for Translation

npm i -g @biesbjerg/ngx-translate-extract
ngx-translate-extract -i ./src -o ./src/assets/i18n/{de,en}.json --clean --format namespaced-json

9. Add ngx-translate-extract as a npm Script

Since we'll be using the string extractor tool during development, we should add it as a npm script:

// package.json

// ...

"scripts": {
  // ...
  "i18n:update": "ngx-translate-extract -i ./src -o ./src/assets/i18n/{de,en}.json --clean --format namespaced-json"
},

// ...

Now we can conveniently run:

npm run i18n:update

10. Inject translate Into the Main App Component

In order to gain access to the Translation Service, we need to include it into the app:

// app.component.ts

// ...
import { TranslateService } from '@ngx-translate/core';

// ...

export class AppComponent {
  // ...

  constructor(translate: TranslateService) {
    translate.setDefaultLang('en');
  }
}

This is possible because we have previously declared that our app.module.ts imports the TranslateModule.

11. Mark Texts for Translation

@ngx-translate offers 3 ways of accessing the Translation Service:

  1. TranslateService
  2. TranslatePipe
  3. TranslateDirective

For more information on these, please consult the @ngx-translate documentation.

For the purpose of this tutorial, we will be using TranslatePipe.

Now that we are able to access the Translation Service, let's mark a text for translation using TranslatePipe.

// app.component.html

<h1>
  {{ "welcome" | translate }}
</h1>

Reloading the application results in the text "welcome" being rendered. That happens because there's no value specified for the "welcome" key in our locale files.

Let's add some translation values to the English locale file:

// src/assets/i18n/en.json

{
  "welcome": "Welcome!",
  ...
}

And to the German locale file:

// src/assets/i18n/de.json

{
  "welcome": "Willkomen!",
  ...
}

Reloading the app will reveal the correct text being rendered for the "welcome" i18n key.

Note:

Marking more texts for translation and running npm run i18n:update will cause new keys to be added to the .json files.

In the same manner, removing a text from the template and running npm run i18n:update will cause the key to be removed (along with its value) from the .json files.

12. Switch Languages

@ngx-translate provides a helper method for switching languages: translate.use().

In order to switch the language dynamically, we need to call Translate Service's use() method.

In order to do that, we declare a new private property translate in AppComponent:

// app.component.ts

// ...
import { TranslateService } from '@ngx-translate/core';

// ...
export class AppComponent {
  translate: TranslateService; // <-- defining translate as a private property

  switchLanguage = (lang: string) => {  // <-- creating a new method
    this.translate.use(lang); // <-- invoking `use()`
  }

  constructor(translate: TranslateService) {
    this.translate = translate;  // <-- binding the injected `TranslatedService` to the local `translate` property
    translate.setDefaultLang('en');
  }
}

And in our template, we add two buttons for invoking switchLanguage():

// app.component.html

// ...
<button (click)="switchLanguage('en')">EN</button>
<button (click)="switchLanguage('de')">DE</button>
// ...

Loading the app will look like this: i18n in Angular using ngx-translate Tutorial: English

And switching to DE will look like this: i18n in Angular using ngx-translate Tutorial: German

13. Enjoy! ๐Ÿ˜Ž


You can find the final version of the code for this tutorial in this repository. ๐Ÿ‘

angular-i18n-ngx-translate's People

Contributors

angular-cli avatar cassilup avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.