@larscom/ngx-translate-module-loader
A loader for @ngx-translate/core that loads multiple translations using http. Each translation file has it's own namespace so the key/value pairs do not conflict with each other. If desired, this can be disabled.
Demo
You can play arround on StackBlitz:
https://stackblitz.com/edit/ngx-translate-module-loader
Dependencies
@larscom/ngx-translate-module-loader
depends on @ngx-translate/core and Angular.
Installation
npm i --save @larscom/ngx-translate-module-loader
Usage
1. create an exported HttpLoaderFactory
function
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { TranslateModule, TranslateLoader } from '@ngx-translate/core';
import {
FileType,
ModuleTranslateLoader,
IModuleTranslationOptions
} from '@larscom/ngx-translate-module-loader';
import { AppComponent } from './app';
export function HttpLoaderFactory(http: HttpClient) {
const options: IModuleTranslationOptions = {
modules: [
{
moduleName: null,
baseTranslateUrl: './assets/i18n',
fileType: FileType.JSON
},
{
moduleName: 'feature1',
baseTranslateUrl: './assets/i18n',
fileType: FileType.JSON
},
{
moduleName: 'feature2',
baseTranslateUrl: './assets/i18n',
fileType: FileType.JSON
}
]
};
return new ModuleTranslateLoader(http, options);
}
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
bootstrap: [AppComponent]
})
export class AppModule {}
Namespacing
By default, each translation file gets it's own namespace based on the moduleName
, what does it mean?
For example with these options:
const options: IModuleTranslationOptions = {
modules: [
{
moduleName: null,
baseTranslateUrl: './assets/i18n',
fileType: FileType.JSON
},
{
moduleName: 'feature1',
baseTranslateUrl: './assets/i18n',
fileType: FileType.JSON
},
{
moduleName: 'feature2',
baseTranslateUrl: './assets/i18n',
fileType: FileType.JSON
}
]
};
Lets say each module in the above example resolves to the following translation:
{
"KEY: "VALUE"
}
The final result would then be:
{
"KEY: "VALUE",
"FEATURE1" : {
"KEY: "VALUE"
},
"FEATURE2" : {
"KEY: "VALUE"
}
}
If you don't need upper case keys, set nameSpaceUppercase
to false in the options because it's upper case by default.
If you don't want to enable namespaces at all, set enableNamespacing
to false
Configuration
export interface IModuleTranslationOptions {
modules: IModuleTranslation[];
enableNamespacing?: boolean;
nameSpaceUppercase?: boolean;
deepMerge?: boolean;
translateError?: (error: any) => void;
}
export interface IModuleTranslation {
moduleName: string;
baseTranslateUrl: string;
fileType: FileType;
}