简体   繁体   中英

Search sensitivity in dropdown (ng-select, angular)

I'm using ng-select with a list of cities, like below:

cities = [
        {id: 1, name: 'MA, Boston'},
        {id: 2, name: 'FL, Miami'},
        {id: 3, name: 'NY, New York', disabled: true},
        {id: 4, name: 'CA, Los Angeles'},
        {id: 5, name: 'TX, Dallas'}
    ];

In the select field, if I type "MA, B" then the field filters to "MA, Boston", which is right.

But, if I type "MA Boston", the field shows no results (many users may miss commas).

Is there a way to make the search function ignore commas, or is less sensitive to them?

Here is a stackblitz with the example above:

https://stackblitz.com/edit/ng-select-mbnngu

You can have a function like:

  searchMe(searchTerm: string, eachObject) {
      let replacedKey = searchTerm.replace(/[,\.-\s]/g, '')
      let newRegEx = new RegExp(replacedKey, 'gi');
      let purgedName = eachObject.name.replace(/[,\.-\s]/g, '')
      if (newRegEx.test(purgedName)) {
        return true
      }
      return false
  }


    <ng-select [items]="cities"
               bindLabel="name"
               [searchFn]="searchMe"
               placeholder="Select city"
               [(ngModel)]="selectedCity">
    </ng-select>

See here: https://stackblitz.com/edit/ng-select-ghnvko?file=app/app.component.ts

A quick hack to do so would be to replace all commas with an empty string.

First, on your component.html, you will need to pass the input property binding for searchFn with your own custom search function .

<ng-select 
  [items]="cities"
  [searchFn]="customSearchFn"
  bindLabel="name"
  placeholder="Select city"
  [(ngModel)]="selectedCity">
</ng-select>

And then, on your component.ts, you will define customSearchFn with the following method. It is a quick hack, but what I did is that I replaced the commas for with an empty string for that particular object. As that for instance MA, Boston will become MA Boston.

customSearchFn(term: string, item) {
  item.name = item.name.replace(',','');
  term = term.toLocaleLowerCase();
  return item.name.toLocaleLowerCase().indexOf(term) > -1;
}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM