Runtime translations in Angular, in three steps
Angular's built-in i18n compiles one bundle per locale. For translations that change without a rebuild, ngx-translate reads them from Lefine at runtime.
- 01
Install the loader dependencies
ngx-translate provides the pipe, the service and the loader contract; core fetches and caches the messages.
terminalbashnpm install @ngx-translate/corenpx lefine loginnpx lefine strings pull -o src/assets/locales# pull writes src/assets/locales/en.json, de.json, ...# Run it again after each publish (or in your build) to refresh them. - 02
Write a TranslateLoader backed by the CDN
TranslateLoader asks for an Observable per language, so rxjs from() around getMessages is the whole adapter.
src/app/lefine.loader.tsimport { Injectable, inject } from '@angular/core'import { HttpClient } from '@angular/common/http'import { TranslateLoader } from '@ngx-translate/core'import { Observable } from 'rxjs'// TranslateLoader's contract: one Observable of messages per language.// The files are the ones `lefine strings pull` wrote.@Injectable({ providedIn: 'root' })export class LefineLoader implements TranslateLoader { private http = inject(HttpClient) getTranslation(lang: string): Observable<Record<string, unknown>> { return this.http.get<Record<string, unknown>>(`/assets/locales/${lang}.json`) }} - 03
Provide it and switch at runtime
One provider in bootstrapApplication, then use() changes language with no page reload and no per-locale build.
src/main.tsimport { bootstrapApplication } from '@angular/platform-browser'import { importProvidersFrom } from '@angular/core'import { provideHttpClient } from '@angular/common/http'import { TranslateModule, TranslateLoader } from '@ngx-translate/core'import { AppComponent } from './app/app.component'import { LefineLoader } from './app/lefine.loader'bootstrapApplication(AppComponent, { providers: [ provideHttpClient(), importProvidersFrom( TranslateModule.forRoot({ defaultLanguage: 'en', loader: { provide: TranslateLoader, useClass: LefineLoader }, }) ), ],})