Angular 5 Pipes and dynamic locale

Viewed 5790

I currently have apps built in angular 4 and would like to upgrade to angular 5. I was reading about how they handle locale in their pipes and it seems like upgrading is no longer an option. From what I can tell they expect you to either 1. manually import a different culture 2. build a separate app for each culture

The problem is that I work for an international company that supports 351 different cultures and we have 15 apps. Is the angular team really saying I have to now build 5265 different applications if I want to keep upgrading as they do? If I went to my boss with that I would probably be thrown out of the room.

In our angularJs apps we just downloaded the $locale service we needed at runtime when the user logged in and set the provider to that. is there nothing like that for Angular? If not I am not sure how an enterprise level app could ever use this language unless the devs were lucky enough to only have to support one culture.

3 Answers

I had the same problem with angular4 I wanted to use AOT with multple languages. This is what I did:

Simple wrapper around a pipe to set the locale.

@Pipe({name: 'datepipe', pure: true})
export class MyDatePipe extends DatePipe implements PipeTransform {
  constructor(private win: WindowRef) {
    super(win.ln);
  }

  transform(value: any, pattern?: string): string | null {
    return super.transform(value, pattern);
  }
}

Service for the locale:

function _window(): any {
  // return the global native browser window object
  return window;
}

@Injectable()
export class WindowRef {
  get nativeWindow(): any {
    return _window();
  }

  //default locale
  public ln = 'en';


  constructor() {
    try {
       if (!isNullOrUndefined(this.nativeWindow.navigator.language) && this.nativeWindow.navigator.language !== '') {
        this.ln = this.nativeWindow.navigator.language;
      }
    }finally {}
  }
}

This worked for angular4 but with angular5 I had to import the supported locales in my main.ts

import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';

registerLocaleData(localeFr);
Related