0

I am using ng-select autocomplete in my angular application for biding country name and country code. Example - If i enter in search box result will be

India - IN

Indonesia - ID

At a time of loading the i retrieved list of all country code with country name as per knowledge it would be done by using custom search feature of ng-select.

Please check my code given bellow -

<ng-select placeholder="Select Countries" class="custom"
  [items]="countryList | async"
  [multiple]="true"
  bindLabel="countryname"
  [searchFn]="searchcountry"
  (change)="onChange($event)"
  [(ngModel)]="selectedCountry">

  <ng-template ng-label-tmp let-item="item" let-clear="clear">
      <span class="ng-value-label">{{item.countryname}}</span>
      <span class="ng-value-icon right" (click)="clear(item)" aria-hidden="true">×</span>
  </ng-template>

  <ng-template ng-option-tmp let-item="item" let-index="index" let-search="searchTerm">
   <span [ngOptionHighlight]="search">  {{item.countryname}} - {{item.countrycode}} </span>
  </ng-template>

ngOnInit() {
   this.countryList = this.caseService.GetCountryList();
}

searchcountry(term: string, item: any) {
   term = term.toLocaleLowerCase();
   return item.countrycode.toLocaleLowerCase().indexOf(term) > -1 || item.countryname.toLocaleLowerCase().includes(term);
}

Please help me how to reach my final output i am very close now just i want to know how to sort to top the record if country code exact match.

Thanks in advance.

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
Satyam Shukla
  • 103
  • 1
  • 2
  • 8

2 Answers2

0

Below code will convert your you JSON object as plain text and then check for the search term in it. I use this solution mainly as pipe where i pass array of object and search term its work like charm.

searchcountry(term: string, item: any) {
        const REGEXP=/("([a-z]+)":)|\[|\]|\{|\}/g;
        term = term.toLocaleLowerCase();
       return term ? item.filter(itm=>{
        let str=JSON.stringify(itm).tolowerCase();
        str=str.replace(REGEXP,'');
        return str.include(term);
       }): item;
      
    }
0

If your country code only consists of two letters (e.g., 'IN' for India), then you could prioritize the country code over the country name as follows:

searchcountry(term: string, item: any) {
   term = term.toLocaleLowerCase();
   return term.length <= 2
      ? item.countrycode.toLowerCase().includes(term)
      : item.countrycode.toLowerCase().includes(term) || item.countryname.toLowerCase().includes(term);
}
tilo
  • 14,009
  • 6
  • 68
  • 85