i18n-iso-countries в Angular 7, отображающие страны в зависимости от текущего языка

Для меня документация i18n-iso-countries немного сбивает с толку. У меня есть проект Angular 7, и я просто хочу отображать все страны для пользователя в регистрационной форме в зависимости от его текущего языка.

Итак, я знаю, что i18nIsoCountries.getNames("en") дает мне все имена и что-то вроде вывода JSON. Текущий язык я могу легко получить с помощью this.translateService.currentLang, но на данный момент у меня есть статический собственный письменный файл JSON только для языков на английском языке, и я отображаю их в своей форме.

Я также хочу отфильтровать страны, в которые я могу написать Ger, и получить предложение Германии. На данный момент это реализовано и работает, но я не знаю, как это сделать с библиотекой.

Компонент регистрации:

    import country from '../../assets/countriesJson.json';

    export interface Country {
      name: string;
      code: string;
    }

    export class RegistrationComponent implements OnInit {
      @ViewChild('stepper') stepper: MatStepper;

      filteredCountries: Observable<Country[]>;
      countryList: Country[] = country.countries;

      ngOnInit() {
        this.filteredCountries = this.personalForm.controls['country'].valueChanges
          .pipe(
            startWith(''),
            map(value => this._filterCountries(value))
          );
      }

      private _filterCountries(value: string): Country[] {
        const filterValue = value.toLowerCase();
        return this.countryList.filter(country => country.name.toLowerCase().indexOf(filterValue) === 0);

        // const filterValue = value.toLowerCase(); Variante für Suche bei dem Begriff nur enthalten ist Ger -> AlGERia
        // return this.countryList.filter(option => option.name.toLowerCase().includes(filterValue));
      }

CountryJson (краткая форма):

    {
    "countries": [
    {"name": "Afghanistan", "code": "AF"},
    {"name": "Åland Islands", "code": "AX"} ]
    }

HTML:

        <mat-form-field class="field-sizing">
          <input matInput required placeholder="{{ 'REGISTRATION.COUNTRY' | translate }}" name="country"
            id="country" [matAutocomplete]="auto" formControlName="country"
            [ngClass]="{ 'is-invalid': g.country.touched && g.country.errors }" />
          <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
            <mat-option *ngFor="let country of filteredCountries | async" [value]="country.name">
              {{country.name}}
            </mat-option>
          </mat-autocomplete>
          <mat-error class="invalid-feedback"
            *ngIf="g.country.touched && g.country.errors && g.country.errors.required">
            {{ 'REGISTRATION.COUNTRY' | translate }} {{ 'VALIDATION.REQUIRED' | translate }}
          </mat-error>
        </mat-form-field>

Так что идея в голове - как-то временно сохранить страны как какие-то данные с i18nIsoCountries.getNames("en")


person CptDayDreamer    schedule 21.05.2019    source источник
comment
Ни у кого нет идей? Я думаю о том, чтобы сделать это как пару ключ-значение и хочу временно сохранить ее, как я уже сказал, но функция getNames(lang: string): i18nIsoCountries.LocalizedCountryNames просто дает ее как строку, даже если ее вывод представляет собой пару ключ-значение.   -  person CptDayDreamer    schedule 27.05.2019


Ответы (1)


Я решил это:

countries = [] as Array<string>
filteredCountries: Observable<string[]>;

ngOnInit() {
 this.startDate.setFullYear(this.startDate.getFullYear() - 18);
 this.buildForm();

 this.filteredCountries = this.personalForm.controls['country'].valueChanges
   .pipe(
     startWith(''),
     map(value => this._filter(value))
   );

 i18nIsoCountries.registerLocale(require("i18n-iso-countries/langs/en.json"));
 i18nIsoCountries.registerLocale(require("i18n-iso-countries/langs/de.json"));

 this.currentLanguage = this.translateService.currentLang;

 indexedArray = i18nIsoCountries.getNames(this.currentLanguage);
 for (let key in indexedArray) {
   let value = indexedArray[key];
   this.countries.push(value);
 }
}

private _filter(value: string): string[] {
 var filterValue;
 if (value) {
   filterValue = value.toLowerCase();
 } else {
   filterValue = "";
 }
 return this.countries.filter(option => option.toLowerCase().startsWith(filterValue));
}

ngAfterContentChecked() {
 this.cdRef.detectChanges();

 if (this.currentLanguage != this.translateService.currentLang) {
   indexedArray = i18nIsoCountries.getNames(this.translateService.currentLang);

   this.countries = [];

   for (let key in indexedArray) {
     let value = indexedArray[key];
     this.countries.push(value);
   }

   this.currentLanguage = this.translateService.currentLang;
   this.personalForm.get('country').updateValueAndValidity();
 }
}

И html-часть:

 <mat-form-field class="field-sizing">
   <input matInput required placeholder="{{ 'REGISTRATION.COUNTRY' | translate }}" name="country"
     id="country" [matAutocomplete]="auto" formControlName="country"
     [ngClass]="{ 'is-invalid': g.country.touched && g.country.errors }" />
   <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
     <mat-option *ngFor="let option of filteredCountries | async" [value]="option">
       {{option}}
     </mat-option>
   </mat-autocomplete>
   <mat-error class="invalid-feedback"
     *ngIf="g.country.touched && g.country.errors && g.country.errors.required">
     {{ 'REGISTRATION.COUNTRY' | translate }} {{ 'VALIDATION.REQUIRED' | translate }}
   </mat-error>
 </mat-form-field>
person CptDayDreamer    schedule 10.06.2019