How to search value in ngselect?

S.Anitha picture S.Anitha · May 15, 2019 · Viewed 8.8k times · Source

From Api, I get the countryName and code as like below

eg:-

  countryName        code
  -----------------------
  India              IND
  United States      USA
  Aruba              ABW

I want to use the ngSelect dropdown and want to display the value like countryName (code) in dropdown.

eg: India (IND)

Question:- I want concatenate the countryName and code. And want to filter the dropdown value based on both countryName and code. Below is the code which I tried. But its not working properly

component.html

  <ng-select [items]="countries" bindLabel="description" bindValue="code"
           clearAllText="Clear" formControlName="countryCode"
          [searchFn]="customSearchFn">
      <ng-template ng-label-tmp let-item="item">
          <span >{{ item.countryName + ' (' + item.code + ')' }}</span>
      </ng-template>
      <ng-template ng-option-tmp let-item="item" let-search="searchTerm" let-index="index">
           <span >{{ item.countryName + ' (' + item.code + ')' }}</span>
      </ng-template>
   </ng-select>

component.ts

getCountry() {
this.lookupService.getCountry().subscribe(
  data => {
    this.countries = data;
  });
 }

customSearchFn

customSearchFn(term: string, item: Lookup) {
  term = term.toLocaleLowerCase();
  return item.code.toLocaleLowerCase().indexOf(term) > -1 || item.countryName.toLocaleLowerCase() === term;
   }

Can anybody give me a solution for Searching?

Answer

Jeremy Benks picture Jeremy Benks · May 15, 2019

I took your code and put it into a Stackblitz. It actually almost worked! I just made a minor change in the search function:

customSearchFn(term: string, item: any) {
    term = term.toLocaleLowerCase();
    return item.code.toLocaleLowerCase().indexOf(term) > -1 || 
           item.countryName.toLocaleLowerCase().indexOf(term) > -1;
}

(both countryName and code use indexOf instead of item.countryName.toLocaleLowerCase() === term)

The only other thing I removed was formControlName="countryCode", that gave me an error "No provider for NgControl". The error makes sense, I have not implemented an NgControl.

Now, ABW gives you Aruba and Aru gives you Aruba too. (That's what you want, right?)