首页 > 解决方案 > Angular Material autocomplete 的 mat-option 有两个可搜索的值

问题描述

我是 Angular 的新手,我有一个 mat-autocomplete 作为搜索字段,我希望我的每个 mat-option 都可以使用 2 个值进行搜索,例如使用名称和 id:

options = [{name: 'x', id: 123},{name: 'y', id:142}] 

任何人都知道我该怎么做?

标签: angularangular-material

解决方案


如果您查看 Angular Material Autocomplete示例,尤其是称为过滤器自动完成的示例,您将看到过滤是如何完成的,并且您可以轻松地将其扩展为过滤多个值。

从示例中(请记住,这里的options数组只是一个字符串数组,因此不会访问/过滤任何属性):

private _filter(value: string): string[] {
  const filterValue = value.toLowerCase();
  return this.options.filter(option => option.toLowerCase().includes(filterValue));
}

我们可以将其重写为以下内容以过滤附加id属性(假设options是具有属性的对象数组nameid):

private _filter(value: string): Option[] {
  const filterValue = value.toLowerCase();
  return this.options.filter(option => String(option.id).toLowerCase().indexOf(filterValue ) > -1 || 
  option.name.toLowerCase().indexOf(filterValue ) > -1);
}

是一个显示上述过滤的 stackblitz。


推荐阅读