i18n-iso-стран в Angular 7 отображает страны в зависимости от текущего языка - PullRequest
0 голосов
/ 21 мая 2019

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

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

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

RegistrationComponent:

    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));
      }

СтраныJson (краткая форма):

    {
    "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")

1 Ответ

0 голосов
/ 10 июня 2019

Я решил это:

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>
...