angularangular-pipeangular-ngselect

How to highlight formatted strings with ng-select?


I am using ng-select and ng-select/ng-option-highlight for a dropdown input field.

In the dropdown I have IBANs. I have formatted the IBANs with a pipe, so that they have a visually appealing form (**** **** **** ****).

I would like to highlight the IBANs as the user types the strings into the search field. But, because of the formatting, highlighting stops at the whitespaces:

'123455' --> "1234 5566 4555 0550"

If I enter a whitespace into the search field, the highlighting disappears.

I have tried removing all whitespaces with a pipe, but it doesn't help:

<ng-select [items]="accounts" 
           bindLabel="name" 
           bindValue="id" 
           [(ngModel)]="selectedAccount">

    <ng-template ng-option-tmp let-item="item" let-search="searchTerm">
        <span [ngOptionHighlight]="search | nospace">{{item.iban | iban}}</span>
    </ng-template>
</ng-select>

import { Pipe, PipeTransform } from "@angular/core";

@Pipe({ name: 'nospace' })
export class NoSpacePipe implements PipeTransform {
  transform(value: any) {
    if (!value) {
      return '';
    }

    return value.replace(/\s/g, "");
  }
}

I have also tried adding the IBAN formatting pipe. It almost works as expected, but not quite.

If the IBAN is '1234 4556 4545 0000' and I enter '123455' it displays "1234 556 4555 0550".

<ng-select [items]="accounts" 
           bindLabel="name" 
           bindValue="id" 
           [(ngModel)]="selectedAccount">

    <ng-template ng-option-tmp let-item="item" let-search="searchTerm">
        <span [ngOptionHighlight]="search | iban">{{item.iban | iban}}</span>
    </ng-template>
</ng-select>

What I would like: '123455' --> "1234 556 4555 0550".

How can I highlight these IBANS correctly?


Solution

  • There is no way to do that, search term is escaped, splitted by space and transformed into regex, see https://github.com/ng-select/ng-select/blob/be0fa91293c5cbec71da0f151639342d1b6f1c76/src/ng-option-highlight/lib/ng-option-highlight.directive.ts#L51

    I think the most reasonable way to do that is to clone NgOptionHighlightDirective and alter highlighting logic.