Angular 自动完成 - 按中单词的首字母过滤

Angular Autocomplete - Filter by starting letters of the words in

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

例子:如果我们输入“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>

根据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