@qntm-code/ng-lazy-translate
v1.1.6
Published
Lazy loaded translation module for Angular
Downloads
8
Maintainers
Readme
@qntm-code/ng-lazy-translate
Lazy loaded translation module for Angular using messageformat.
Installation
npm i @qntm-code/ng-lazy-translate
Usage - Standalone Components
1. Create providers
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig).catch(err => console.error(err));
import { provideHttpClient } from '@angular/common/http';
import { ApplicationConfig } from '@angular/core';
import { provideLazyTranslate } from '@qntm-code/ng-lazy-translate';
export const appConfig: ApplicationConfig = {
providers: [
provideHttpClient(),
provideLazyTranslate({
defaultLanguage: 'en',
languages: [
{
code: 'en',
displayValue: 'English',
},
{
code: 'fr',
displayValue: 'Français',
},
],
translationAssetPaths: {
'en.common': 'asset/i18n/en/common.json',
'fr.common': 'asset/i18n/fr/common.json',
},
missingTranslationHandler: (language: string, key: string) => console.error(`Custom handler: Could not find ${key} in ${language}`),
missingFileHandler: (namespace: string, language: string) =>
console.error(`Custom handler: CFile with namespace ${namespace} not found for language ${language}`),
}),
],
};
Usage - Within a Module
1. Import Module
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { NgLazyTranslateModule } from '@qntm-code/ng-lazy-translate';
@NgModule({
imports: [
HttpClientModule,
NgLazyTranslateModule.forRoot({
defaultLanguage: 'en',
languages: [
{
code: 'en',
displayValue: 'English',
},
{
code: 'fr',
displayValue: 'Français',
},
],
translationAssetPaths: {
'en.common': 'asset/i18n/en/common.json',
'fr.common': 'asset/i18n/fr/common.json',
},
}),
],
})
export class AppModule {}
2. Import module in component
import { Component } from '@angular/core';
import { NgLazyTranslateModule } from '@qntm-code/ng-lazy-translate';
@Component({
standalone: true,
imports: [NgLazyTranslateModule],
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent {}
Using pipe in a template
<p>{{ 'common.hello_world' | translate }}</p>
Using the service in a component/service
import { Injectable } from '@angular/core';
import { LazyTranslateService } from '@qntm-code/ng-lazy-translate';
@Injectable()
export class MyService {
constructor(private readonly translateService: LazyTranslateService) {}
public doSomething(): Observable<string> {
return this.translateService.translate('common.hello_world');
}
}
LazyTranslateModuleConfig
Whether you use the standalone components or the module, the LazyTranslateModuleConfig options are the same.
| Option | Type | Description | Mandatory | Default |
| ------------------------- | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | --------- | ---------------------------- |
| defaultLanguage | string | The default language to use if no language is specified | Yes | N/A |
| languages | Language[] | The list of languages to support | Yes | N/A |
| translationAssetPaths | TranslationAssetPaths | The list of translation assets to load. The key is the language and the translation file name. | Yes | N/A |
| useDefaultLanguage | boolean | Whether to use the default language if the specified language is not found | No | true
|
| enableLogging | boolean | Whether to enable logging of missing translations | No | true
|
| missingTranslationHandler | (language: string, key: string) => void | A custom handler to use when a translation is not found. If not specified, the default handler will be used. | No | Will console.error a message |
| missingFileHandler | (namespace: string, language: string) => void | A custom handler to use when a translation file is not found. If not specified, the default handler will be used. | No | Will console.error a message |
Language
| Option | Type | Description | | ----------- | ------ | ------------------ | | code | string | The language code. | | displayName | string | The language name. |
TranslationAssetPaths
| Option | Type | Description |
| ------ | ------ | ---------------------------------------------------------------------------- |
| key | string | The language and translation file name. For example: en.common
or fr.app
|
| value | string | The path to the translation file. e.g assets/i18n/en.common.json
|
Translation files
Translation files must be in JSON format and have the following structure:
{
"hello_world": "Hello World!"
}
You can also use nested keys:
{
"greetings": {
"hello_world": "Hello World!"
}
}
You can then access this nest value like so:
In a template:
{{ 'common.greetings.hello_world' | translate }}
In a component/service:
this.translateService.translate('common.greetings.hello_world');
The translation service uses messageformat to format the translation., which allows you to pass values to your translated text:
{
"greetings": {
"hello_world": "Hello {name}! It is {time}"
}
}
Template:
{{ 'common.greetings.hello_world' | translate: { name: 'John', time: '10:00' } }}
Component/Service:
this.translateService.translate('common.greetings.hello_world', { name: 'John', time: '10:00' });
Default value
If you want to provide a default value for when a translation is not found in any language, you can do so by passing it as the last parameter to the translate pipe or function:
Template:
{{ 'common.greetings.hello_world' | translate: { name: 'John', time: '10:00' }: 'Hello, this is my default string' }}
or without values:
{{ 'common.greetings.hello_world' | translate: 'Hello, this is my default string' }}
Component/Service:
this.translateService.translate('common.greetings.hello_world', { name: 'John', time: '10:00' }, 'Hello, this is my default string');
or without values:
this.translateService.translate('common.greetings.hello_world', undefined, 'Hello, this is my default string');