用于KeyValue和AutoComplete的角度过滤器管道

时间:2019-06-11 01:41:20

标签: javascript angular typescript angular-pipe

首先,我想显示带有此管道的国家/地区并用插入的字符过滤它们,并且我需要ISO代码来显示这些国家/地区的标志。问题是我想使用一个包含所有具有ISO代码和内容的国家的图书馆。这具有键值形式。

首先,我将此数据导出到var,以便能够使用该数据。

export var indexedArray: { [key: string]: string } 
countryStuff: Country; //currently not used

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

export interface Country { //currently not used
  [key: string]: 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);
 }
}

在html中,我可以这样使用:

  <mat-option *ngFor="let item of countryStuff | keyvalue:keepOriginalOrder" [value]="item.key">
     Key: <b>{{item.key}}</b> and Value: <b>{{item.value}}</b>
  </mat-option>

我也可以使用正常方式,但是完全没有键值方式,就像Angular示例所说的那样(没有TS逻辑):

 <mat-option *ngFor="let option of filteredCountries | async" [value]="option">
    <span class="flag-icon flag-icon-de flag-icon-squared"></span>
    {{option}}
 </mat-option>

这只是给我完整的国家名称,例如阿尔及利亚之类的东西。

我在https://long2know.com/2017/04/angular-pipes-filtering-on-multiple-keys/处找到了一个主意,但出于我的目的无法更改。如果我可以过滤 key value ,那可能会更加完美,因此,对于德国的值,也许可以使用“ DE”,对于德国的值可以使用“ Ger”。现有的管道似乎无法实现。

根据要求编辑(过滤):

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

还更新了ngOnInit()

1 个答案:

答案 0 :(得分:0)

我可以使用i18n库甚至flag-icon-css

TypeScript(过滤器类):

@Pipe({
  name: 'filterLanguages'
})
export class FilterLanguages implements PipeTransform {
  transform(items: any, filter: any, isAnd: boolean): any {
    if (filter && Array.isArray(items)) {
      let filterKeys = Object.keys(filter);
      if (isAnd) {
        return items.filter(item =>
          filterKeys.reduce((memo, keyName) =>
            (memo && new RegExp(filter[keyName], 'gi').test(item[keyName])) || filter[keyName] === "", true));
      } else {
        return items.filter(item => {
          return filterKeys.some((keyName) => {
            return new RegExp(filter[keyName], 'gi').test(item[keyName]) || filter[keyName] === "";
          });
        });
      }
    } else {
      return items;
    }
  }
}

HTML:

<mat-form-field class="field-sizing">
  <input matInput required placeholder="{{ 'REGISTRATION.COUNTRY' | translate }}" name="country"
    id="country" [matAutocomplete]="auto" formControlName="country" [value]="filterText" />
  <mat-autocomplete autoActiveFirstOption #auto="matAutocomplete">
    <mat-option *ngFor="let item of countries | filterLanguages:{ name: filterText, iso: filterText, flagId: filterText } : false" [value]="item.name">
      <span class="flag-icon flag-icon-{{item.flagId}} flag-icon-squared"></span>
      {{ item.name }} - {{ item.iso }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>

TypeScript(组件):

export var countryList: {
  [key: string]: string
}

declare const require;

export class YourComponent implements OnInit {

  countries = [] as Array<any>
  currentLanguage: string;
  filterText: string;

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

    this.currentLanguage = this.translateService.currentLang;
    countryList = i18nIsoCountries.getNames(this.currentLanguage);

    this.buildForm();
    this.createCountries();

    this.personalForm.controls['country']
      .valueChanges
      .pipe(debounceTime(100))
      .pipe(distinctUntilChanged())
      .subscribe(term => {
        this.filterText = term;
      });
  }

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

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

      this.createCountries();

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

  createCountries() {
    this.countries = [];
    for (let key in countryList) {
      var countryName: string = countryList[key];
      var isoValue: string = key;
      var isoLowerValue: string = key.toLowerCase();

      this.countries.push({ name: countryName, iso: isoValue, flagId: isoLowerValue })
    }
  }

您需要i18​​n库,并在我的示例中使用formControl。

相关问题