Member-only story

Angular: Simple translation from scratch

Translation must be a way simpler

Allen Kim
3 min readSep 20, 2024
Photo by Sandy Millar on Unsplash

Angular translation must not be that complicated. Every time when I upgrade Angular I encounter with lots of errors because of unknown module errors. Thus, I provide the simplest translation solution without thinking of edge cases, e.g. dynamic translation etc.

1. Create a TranslateModule

Here are classes that I need in this module.

  • TranslateService: Provides translation from the given key.
  • TranslateDirective: TranslateService used as a directive.
  • TranslatePipe: TranslateService used as a pipe.
  • TranslateModule: For module import.

TranslateService

import { Inject, Injectable, Optional } from "@angular/core";
declare var window: any;

@Injectable()
export class TranslateService {
lang: string = 'en';
translations: any = {};

constructor(@Inject('config') private config: any) {
config.lang && (this.lang = config.lang);
config.translations && (this.translations = config.translations);
}

static getBrowserLang() {
return window.navigator.language ||
window.navigator.browserLanguage ||
window.navigator.userLanguage ||
window.navigator.languages?.[0]…

--

--

Allen Kim
Allen Kim

No responses yet