Search code examples
angularangular-materialangular7highlightangular-pipe

Angular mat-autocomplete with highlight pipe issue


I have one scenario where I'm using mat-autocomplete with custom highlight pipe. Everything works fine, issue is coming when I select a value from autocomplete and then I try to reset the form, form is getting reset but the value in the autocomplete is still highlighted.

highlight.pipe.ts

transform(text: string, search): string {
    const pattern = search
      .replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&")
      .split(' ')
      .filter(t => t.length > 0)
      .join('|');
    const regex = new RegExp(pattern, 'gi');
    return search ? text.replace(regex, match => `<b>${match}</b>`) : text;
  }

component.html

<form class="example-form">
    <mat-form-field class="example-full-width">
        <input matInput placeholder="State" aria-label="State" [matAutocomplete]="auto" [formControl]="stateCtrl">
        <mat-autocomplete #auto="matAutocomplete">
            <mat-option *ngFor="let state of filteredStates | async" [value]="state.name">
        <span [innerHTML]="state.name | highLight: toHighlight"></span>
                <span></span>
            </mat-option>
        </mat-autocomplete>
    </mat-form-field>
</form>

Stackblitz Demo

On click of reset I don't want any value to be highlighted. Is there any way to fix this issue.

Thanks in advance


Solution

  • You can pass multiple arguments to a pipe, so you could pass the value of stateCtrl, and add that to your condition to check if value exists there as well:

    <span [innerHTML]="state.name | highLight: toHighlight : stateCtrl.value"></span>
    

    and then do the additional check for that value:

    transform(text: string, search: string, ctrlValue: string): string {
      // ....
      return (search && ctrlValue) ? text.replace(regex, match => `<b>${match}</b>`) : text;
    }
    

    Your forked STACKBLITZ