2
votes

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

2
I couldn't even reproduce the issue in the stackblitz? I started typing, chose an option and clicked reset. When clicking autocomplete again, nothing was highlighted. Am I missing some step?AJT82
i just added the fix given by imrane , you can reproduce the issue by removing toHighlight="" in reset method and by commenting out keyup method on input tagAnil Kumar Reddy A
okay, but then your issue is solved, right? :)AJT82
I don't think it's an ideal fix. it was just a temporary fix. Try if you can give a permanent fixAnil Kumar Reddy A

2 Answers

2
votes

you have to just reset toHighlight='' again in the reset function... but you got another annoying small problem, after you delete what you typed, even if the field is empty, it still remembers the last caracter and highlights it ..so your solution now is to always reset the form but you gotta work on that

2
votes

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