9

I want to merge two API fields "code and name" in ng-select dropdown. For example:-

  Code       : MI

  name       : MI 3sPrime

 Format      : MI - MI 3sPrime

I used the below code for dropdown

Component.Html

<ng-select [items]="products" bindLabel="code" bindValue="id"
                placeholder="Select Goods Receipt" clearAllText="Clear" formControlName="productId" [searchFn]="customSearchFn">

                  <ng-template ng-label-tmp let-item="item">
                    <span [ngOptionHighlight]="search">{{ item.code }} - {{ item.name }}</span>
                  </ng-template>

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

</ng-select>

Component.ts

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

Searching: Code and name is fetching while searching. But I want to search for code , name and given format(Code - name)

Below are the diagrams

enter image description here

Here, While I search the "MI -" , Searching not works

enter image description here

Searching should apply for the format code - name..Which means when I type MI -, filteration have to work. Is there any method? Can anybody help me?

1 Answer 1

9

try this

  customSearchFn(term: string, item: any) {
    term = term.toLocaleLowerCase();
    return item.code.toLocaleLowerCase().indexOf(term) > -1 || 
    item.name.toLocaleLowerCase().indexOf(term) > -1 || 
    (item.code + " - " + item.name).toLocaleLowerCase().indexOf(term) > -1;
 }
Sign up to request clarification or add additional context in comments.

2 Comments

Use an arrow function if you want "this" to be defined. customSearchFn = (term: string, item: any) => { // Can use this.something here }
at html -> <ng-select [searchFn]="customSearchFn">

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.