Angular Autocomplete - 通过单词的起始字母过滤

标签 angular typescript filter autocomplete

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

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

怎么做?

enter image description here

<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()));
  };
}

Sample Solution on StackBlitz

关于Angular Autocomplete - 通过单词的起始字母过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67980568/

相关文章:

javascript - 为什么 Angular 子路由除了第一次之外不渲染组件?

java - 使用 Java 和 Angular2 进行 Spring Security 登录

arrays - 将函数传递给数组过滤器函数错误 - Swift 4

r - 按 R 中的年份和列号过滤

python - SQLAlchemy一对多关系,如何过滤集合

html - 在 <img> 中调用一个函数来定义 src 的路径

Angular 8 - POST + 重定向与提交 HTML <form> 完全一样,但不使用 DOM

javascript - 在呈现 View 之前从父级设置子组件属性

javascript - 在 angularjs 中注册服务(使用 typescript )

if-statement - 访问 typescript 联合类型中的不同属性