TranslateLoader API
Translate Loader API
The loader is responsible for providing translations to the application. It can deliver either embedded translations or load them from a server.
There are several loaders already available as plugins. So in most
cases, you’ll not need to create your own. See Installation
on how to use the default loader @ngx-translate/http-loader
.
You might also find 3rd party loaders in the plugins section.
The ngx-translate can be configured with a loader which loads translation files at runtime.
To implement your own loader, create a class derived from this interface:
export abstract class TranslateLoader { abstract getTranslation(lang: string): Observable<any>;}
The getTranslation()
receives the language code as input and
has to return a promise the resolves to a translation object.
{ "app.hello": "Hello World!"}
Standalone Components
To configure ngx-translate to use your loader
change the configuration in provideTranslateService()
function in your app.config.ts:
...import {provideTranslateService, TranslateLoader} from "@ngx-translate/core";...
export const appConfig: ApplicationConfig = { providers: [ ... provideTranslateService({ loader: { provide: TranslateLoader, userClass: YourLoader }, }) ],};
If you are using the HttpClient
, use a factory method to initialise it:
import {ApplicationConfig, provideZoneChangeDetection} from "@angular/core";import {provideHttpClient} from "@angular/common/http";import {provideTranslateService, TranslateLoader} from "@ngx-translate/core";import {TranslateHttpLoader} from '@ngx-translate/http-loader';import {HttpClient} from '@angular/common/http';
const httpLoaderFactory: (http: HttpClient) => TranslateLoader = (http: HttpClient) => new YourLoader(http);
export const appConfig: ApplicationConfig = { providers: [ ... provideHttpClient(), provideTranslateService({ loader: { provide: TranslateLoader, useFactory: httpLoaderFactory, deps: [HttpClient], }, }) ],};
ngModules
To configure the TranslateModule
to use your loader
change the configuration in TranslateModule.forRoot()
:
TranslateModule.forRoot({ loader: { provide: TranslateLoader, useClass: YourLoader }})
If you are using the HttpClient
, use a factory method to initialise it:
const httpLoaderFactory: (http: HttpClient) => TranslateHttpLoader = (http: HttpClient) => new YourLoader(http, yourconfig );
TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: httpLoaderFactory, deps: [HttpClient], },})