You can find a demo implementation here.
See here on more information how to set up typesafe-i18n.
npm install typesafe-i18nInitialize typesafe-i18n by running
npx typesafe-i18n --setup-autoYou could configure your development script to run the generator in parallel to ng serve by using npm-run-all.
{
"scripts": {
"dev": "npm-run-all --parallel start typesafe-i18n",
"typesafe-i18n": "typesafe-i18n",
"start": "ng serve",
}
}The generator will create a custom Angular Service inside i18n.service.ts that you can use inside your application.
That's it. You can then start using typesafe-i18n inside your Angular components.
greeting.component.ts
import { Component } from '@angular/core'
import { TranslationFunctions } from '../i18n/i18n-types'
import { I18nService } from '../i18n/i18n.service'
@Component({
selector: 'app-greeting',
templateUrl: './greeting.component.html',
})
export class GreetingComponent {
constructor(private i18nService: I18nService) { }
get LL(): TranslationFunctions {
return this.i18nService.LL
}
}greeting.component.html
<p>{{ LL.HI({ name: 'John' }) }}</p>The service gives you access to following variables:
An initialized i18nObject you can use to translate your app.
A string containing the current selected locale.
A function to set another locale for the context.
import { Component } from '@angular/core'
import { Locales } from '../i18n/i18n-types'
import { locales } from '../i18n/i18n-util'
import { I18nService } from '../i18n/i18n.service'
@Component({
selector: 'app-language-switcher',
templateUrl: './language-switcher.component.html',
})
export class LanguageSwitcherComponent {
constructor(private i18nService: I18nService) { }
setLocale(locale: Locales): void {
// TODO: load locales (https://github.com/ivanhofer/typesafe-i18n/tree/main/packages/generator#loading-locales)
// e.g. take a look at the example implementation (https://github.com/ivanhofer/typesafe-i18n/blob/main/packages/adapter-angular/example/src/app/app.component.ts#L37)
this.i18nService.setLocale(locale)
}
}For more information about typesafe-i18n, take a look at the main repository.