Regular User
Regular User

Reputation: 695

Region or country in ngx-translate (Angular)

I've searched yesterday and today, but no luck. Maybe I'm just missing it. How do I have different translations for english in the US, GB, and AU?

I'm not sure if the terminology for this would be called region, country, or locale. Locale usually means language and region together, but that doesn't seem to be the case for ngx-translate.

EDIT:

I was able to use region information in the getTranslation() call to direct to the correct translation file. Since the region was not provided by javascript/angular, I could only accomplish this by checking the domain name for the website (I have different domain names for different countries). Without different domain names, I don't know how to determine the region/country.

Upvotes: 0

Views: 3077

Answers (1)

Daniel
Daniel

Reputation: 1042

At your module import the translations:

TranslateModule.forRoot({
      loader: {
        provide: CustomTranslateLoader,
      }
    }),

CustomTranslateLoader, just replace "ca, en, es" with the languages you want

import { TranslateLoader } from '@ngx-translate/core';
import { Observable } from 'rxjs';
import es from '../../locales/es/translation.json';
import en from '../../locales/en/translation.json';
import ca from '../../locales/ca/translation.json';

export class CustomTranslateLoader implements TranslateLoader {
    public getTranslation(lang: string): Observable<any> {
        return Observable.create(observer => {
            switch (lang) {
                case 'es':
                    observer.next(es);
                    break;
                case 'en':
                    observer.next(en);
                    break;
                case 'ca':
                    observer.next(ca);
                    break;
            }

            observer.complete();
        });
    }
}

and finally, on your AppComponent put one by default and try to use the one that the user has in his browser:

constructor(
    private translate: TranslateService,
  ) {
    translate.setDefaultLang('es');
    translate.use(translate.getBrowserLang());
  }

list of all locales: List of All Locales and Their Short Codes?

Upvotes: 1

Related Questions