Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search value in ngselect?

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?

like image 775
S.Anitha Avatar asked May 15 '19 11:05

S.Anitha


People also ask

How does ng-select work?

The ng-selected directive sets the selected attribute of an <option> element in a <select> list. The option will be selected if the expression inside the ng-selected attribute returns true. The ng-selected directive is necessary to be able to shift the value between true and false .


1 Answers

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?)

like image 155
Jeremy Benks Avatar answered Oct 18 '22 11:10

Jeremy Benks