mat-autocomplete filter to hightlight partial string matches

后端 未结 1 657
予麋鹿
予麋鹿 2021-02-05 10:22

I am trying to achieve a filter with mat-autocomplete that is similar to the following example;

trade input example

So I am trying to achieve the fu

1条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 11:00

    You can use a custom pipe to highlight the partial match whenever the user types in something in the filter.

    @Pipe({ name: 'highlight' })
    export class HighlightPipe implements PipeTransform {
      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 => `${match}`) : text;
      }
    }
    

    Demo

    0 讨论(0)
提交回复
热议问题