如何在ngselect中搜索值?

S.A*_*tha 6 angular-ngselect angular angular5 angular7

从 Api,我得到 countryName 和代码如下

例如:-

  countryName        code
  -----------------------
  India              IND
  United States      USA
  Aruba              ABW
Run Code Online (Sandbox Code Playgroud)

我想使用 ngSelect 下拉列表并希望在下拉列表中显示 countryName (code) 之类的值。

例如:印度(IND)

问题:-我想连接countryName和code。并希望根据countryName 和 code过滤下拉值。下面是我试过的代码。但它不能正常工作

组件.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>
Run Code Online (Sandbox Code Playgroud)

组件.ts

getCountry() {
this.lookupService.getCountry().subscribe(
  data => {
    this.countries = data;
  });
 }
Run Code Online (Sandbox Code Playgroud)

自定义搜索Fn

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

有人可以给我一个搜索解决方案吗?

Jer*_*nks 10

我把你的代码放到了Stackblitz 中。它实际上几乎起作用了!我只是在搜索功能上做了一个小改动:

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

(countryName 和 code 都使用 indexOf 而不是item.countryName.toLocaleLowerCase() === term)

我删除的唯一另一件事是formControlName="countryCode",这给了我一个错误“NgControl 没有提供者”。错误是有道理的,我还没有实现 NgControl。

现在,ABW 为您提供 Aruba,Aru 也为您提供 Aruba。(这就是你想要的,对吧?)