在这里,我在自动完成下拉列表中获得了国家/地区列表,并尝试通过国家名称的开头字母来过滤这些国家/地区。
示例:如果我们输入“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 ,
输入 | 说明 |
---|---|
自定义过滤器 | 自定义过滤功能。您可以使用它来提供自己的过滤功能,例如模糊匹配过滤,或完全禁用过滤(只需通过 (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>
.component.ts
export class AppComponent {
...
customFilter = function(countries: any[], query: string): any[] {
return countries.filter(x => x.name.toLowerCase().startsWith(query.toLowerCase()));
};
}
关于Angular Autocomplete - 通过单词的起始字母过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67980568/