NgxGlagolize is an Angular library for handling translations and localization in your Angular applications.
To install NgxGlagolize, run the following command:
ng add ngx-glagolize
You have to provide HttpClient so the library works properly
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes),
provideHttpClient(), //Provide this
provideNgxGlagolizeConfig({fallbackLanguage: 'en'})
],
};
The default config for NgxGlagolize is provided automatically after ng add
.
You can change the fallback language for the case the user chooses a language that is not provided by you.
First of all you can generate languge files via following command
ng generate ngx-glagolize:language --code de --project demo-app
This command generates a de.json languge file in your public directory. This file can be filled wit key value pairs.
{
"key": "value"
}
In case you need an alternative for plural forms, you can use the following structure
{
"key": {"one": "value", "other":"values"}
}
Then next step should be a call that initiales the load of a language file. app.component.ts would be a good place to do that:
ngxGlagolizeService = inject(NgxGlagolizeService);
constructor() {
this.ngxGlagolizeService.init('en');
}
There are two ways to provide some translation strings:
-
Using the NgxGlagolizeDirective
<div ngxGlagolize key="test">test translation</div>
The key parameter is required. This key is extracted from the current loaded language file. There is also an optional parameter to determine whether to use a singular or plural form of the word.
<div ngxGlagolize key="test" [plural]="true">test translation</div>
-
Using the NgxGlagolizeService In the component.ts you can inject the NgxGlagolizeService und use the
.get(key)
method to retrieve a languge string
Finally you don't have to write all the keys down. There is a command that extracts all used keys from your project and adds them to the languge files:
ng generate ngx-glagolize:extract-keys --project demo-app