Angular Autocomplete - 按单词的开头字母进行过滤

use*_*495 3 autocomplete filter typescript angular

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

示例:如果我们输入“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>
Run Code Online (Sandbox Code Playgroud)

Yon*_*hun 8

根据Angular AutoComplete 输入

输入 描述
自定义过滤器 自定义过滤功能。您可以使用它来提供您自己的过滤功能,例如模糊匹配过滤,或完全禁用过滤(只需将 (items) => items 作为过滤器传递)。不要更改给定的 items 参数,而是返回过滤列表。

您可以定义自定义过滤器逻辑并将其传递给[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>
Run Code Online (Sandbox Code Playgroud)

.component.ts

export class AppComponent {
  ...

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

StackBlitz 上的示例解决方案