Search code examples
angularselectangular-ngselect

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


Solution

  • 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