【问题标题】:Angular Filter Pipe for KeyValue and AutoCompleteKeyValue 和 AutoComplete 的 Angular 过滤器管道
【发布时间】:2019-06-11 01:41:20
【问题描述】:

首先我想用这个管道显示国家并用插入的字符过滤它们,我需要 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/,但我无法为我的目的更改它。如果我可以过滤 keyvalue,那将更加完美,所以也许“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()

【问题讨论】:

  • DE和Ger分别代表key和value?
  • 是的,抱歉。我编辑那个。 @wentjun
  • 没人知道吗?我不擅长管道..
  • 抱歉,我可以知道过滤的方式和位置吗?
  • @wentjun 完成。如果你还需要什么告诉我

标签: javascript angular typescript angular-pipe


【解决方案1】:

我可以使用 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 })
    }
  }

您需要 i18n 库,并且在我的示例中需要一个 formControl。

【讨论】:

    猜你喜欢
    • 2020-07-01
    • 2017-11-29
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 2017-03-02
    • 1970-01-01
    • 2016-01-12
    相关资源
    最近更新 更多