Skip to content

viatcheslav-zadorozhniy/ng-i18n

Repository files navigation

Angular built-in i18n

Table of contents

Benefits

  • native support by the Angular team
  • ICU expressions support
  • ability to validate translations during CI/CD
  • integration with built-in pipes (date, currency, etc.)
  • smaller bundle size - translations are part of a code
  • support for markup in translation (as a translation token)
    • throws an error in case of unexpected markup placeholders
    • directly used tags in the translation will be securely escaped
    • the markup is part of the template, so it's available for binding
  • flexibility
    • separate bundle for each locale
    • or single bundle with run-time translation
    • or even dynamic locale change (with some conventions)
  • translator-friendly

How does it work?

  • mark text for translation in a template via i18n or i18n-* attributes
  • mark text for translation in a component via $localize tagged template
  • marked text will be replaced with translations during the build
    • or during the bootstrap in case of runtime translation
  • LOCALE_ID value and locale data will be applied automatically during the build
    • or should be done manually for runtime translation

Deploy multiple locales

Demo

Mark text for translation:

More details

Extract translatable text

Add extract-i18n configuration to the angular.json.

E.g.

...
"architect": {
  "extract-i18n": {
    "builder": "@angular-devkit/build-angular:extract-i18n",
    "options": {
      "browserTarget": "app:build",
      "outFile": "locales/en.xlf",
      "format": "xlf2"
    }
  }
}
...

Add extract-i18n script to the package.json.

E.g.

{
  "scripts": {
    "extract-i18n": "ng extract-i18n"
  }
}

Execute the command via npm run extract-i18n.

Then you will have an XLIFF file with the extracted text (e.g. en.xlf).

More details

Update build configuration

  • add i18n details (source locale, supported locales and their translations)
  • update build options (add localization, report on missing/duplicate translations)
  • set-up locale-specific builders (for development)

E.g.

...
"i18n": {
  "sourceLocale": "en",
  "locales": {
    "he": {
      "translation": "locales/he.xlf"
    },
    "uk": {
      "translation": "locales/uk.xlf",
      "baseHref": "/uk/"
    }
  }
},
"architect": {
  "build": {
    "options": {
      "localize": true,
      "i18nMissingTranslation": "error",
      "i18nDuplicateTranslation": "error"
    },
    "configurations": {
      "development": {
        "localize": ["en"]
      },
      "he": {
        "localize": ["he"]
      },
      "uk": {
        "localize": ["uk"]
      }
    }
  }
}
...

More details

Add locale-specific serve scripts to the package.json (for development).

E.g.

{
  "scripts": {
    "start:he": "ng serve -c=he",
    "start:uk": "ng serve -c=uk"
  }
}