【问题标题】:Angular Autocomplete - Filter by starting letters of the words inAngular Autocomplete - 通过单词的起始字母过滤
【发布时间】:2021-08-30 23:15:05
【问题描述】:

在这里,我在自动完成下拉列表中获得了国家/地区列表,并尝试通过国家名称的开头字母来过滤这些国家/地区。

示例:如果我们输入“Aus”,所有带有“aus”的国家名称都会被过滤掉。 (见截图)。我只想过滤“澳大利亚和奥地利”或任何其他以“Aus”开头的国家/地区名称。

怎么做?

<ng-autocomplete #countryList formControlName="locationCountry" [data]="countries"
   min-length="1" [searchKeyword]="countrykeyword"
   [initialValue]="countrykeyword"
   (selected)='selectEventCountry($event);onLocationSubmit();'
   (inputCleared)='onCountryCleared($event, false)'
   [itemTemplate]="countryListTemplate"
   [notFoundTemplate]="notFoundTemplate" placeHolder="Enter Country">
</ng-autocomplete>

【问题讨论】:

  • 你可以使用自定义管道,查看这个解决方案stackoverflow.com/a/49670236/10607908
  • 我不可能知道您使用的是“什么”自动完成功能,请检查是否有办法重新放置“搜索功能”-如果有 @Input 或类似的-跨度>

标签: angular typescript filter autocomplete


【解决方案1】:

根据Angular AutoComplete Inputs

Input Description
customFilter Custom filter function. You can use it to provide your own filtering function, as e.g. fuzzy-matching filtering, or to disable filtering at all (just pass (items) => items as a filter). Do not change the items argument given, return filtered list instead.

您可以定义自定义过滤器逻辑并将其传递给[customFilter]@Input 属性。


解决方案

.component.html

<ng-autocomplete #countryList formControlName="locationCountry" 
    [data]="countries" 
    min-length="1"
    [searchKeyword]="countrykeyword" 
    [initialValue]="countrykeyword"
    (selected)='selectEventCountry($event);onLocationSubmit();' 
    (inputCleared)='onCountryCleared($event, false)'
    [itemTemplate]="countryListTemplate" 
    [notFoundTemplate]="notFoundTemplate" 
    placeholder="Enter Country"
    [customFilter]="customFilter">
</ng-autocomplete>

.component.ts

export class AppComponent {
  ...

  customFilter = function(countries: any[], query: string): any[] {
    return countries.filter(x => x.name.toLowerCase().startsWith(query.toLowerCase()));
  };
}

Sample Solution on StackBlitz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-08
    相关资源
    最近更新 更多