i18n-iso-countries in Angular 7 根据当前语言显示国家

i18n-iso-countries in Angular 7 displaying countries depending on current language

对我来说,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));
      }

CountriesJson(缩写形式):

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

以某种方式暂时将国家/地区保存为某种数据

我解决了:

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>