如何解决根据首字母匹配搜索或过滤数据
我正在使用 ng-select library 来实现搜索下拉菜单。我正在尝试实现一个自定义函数,该函数将在我开始输入时通过下拉列表中的第一个匹配字母来过滤项目。例如,如果用户输入“A”,它应该只在以“A”开头的下拉列表中显示人物姓名。
我创建了一个 stackblitz 示例。我尝试使用 Array.filter() 函数,但过滤器功能不起作用,因为我从我的 'customSearchFn 返回了“item” >' 不在数组中。有没有不使用过滤功能的方法来实现?
hello.component.ts
import { Component,Input } from '@angular/core';
@Component({
selector: 'hello',template: `
<ng-select
[items]="people"
bindLabel="name"
autofocus
[searchFn]="customSearchFn"
>
</ng-select>
`,styles: [
`
h1 {
font-family: Lato;
}
`
]
})
export class HelloComponent {
@input() name: string;
people = [
{
id: '5a15b13c36e7a7f00cf0d7cb',index: 2,isActive: true,picture: 'http://placehold.it/32x32',age: 23,name: 'Karyn Wright',gender: 'female',company: 'ZOLAR',email: 'karynwright@zolar.com',phone: '+1 (851) 583-2547'
},{
id: '5a15b13c2340978ec3d2c0ea',index: 3,isActive: false,age: 35,name: 'Rochelle Estes',disabled: true,company: 'EXTRAWEAR',email: 'rochelleestes@extrawear.com',phone: '+1 (849) 408-2029'
},{
id: '5a15b13c2b1746e12788711f',index: 11,age: 25,name: 'Nguyen Elliott',gender: 'male',company: 'PORTALINE',email: 'nguyenelliott@portaline.com',phone: '+1 (905) 491-3377'
},{
id: '5a15b13c605403381eec5019',index: 12,age: 31,name: 'Mills Barnett',company: 'FARMEX',email: 'millsbarnett@farmex.com',phone: '+1 (882) 462-3986'
},{
id: '5a15b13c947c836d177aa85c',index: 14,age: 29,name: 'Yvette Navarro',company: 'KINETICA',email: 'yvettenavarro@kinetica.com',phone: '+1 (807) 485-3824'
},{
id: '5a15b13c5dbbe61245c1fb73',index: 15,age: 20,name: 'Elisa Guzman',company: 'KAGE',email: 'elisaguzman@kage.com',phone: '+1 (868) 594-2919'
}
];
customSearchFn(term: string,item: any) {
console.log(term);
console.log(item);
}
}
解决方法
您只需将 customSearchFunction 修改为:
customSearchFn(term: string,item: any) {
// check if the name startsWith the input,everything in lowercase so "a" will match "A"
return item.name.toLowerCase().startsWith(term.toLowerCase())
}
仅供参考,您列表中的每个项目都会调用自定义函数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。