Highlight the search text - angular 2

前端 未结 7 868
心在旅途
心在旅途 2020-12-01 05:22

A messenger displays the search results based on the input given by the user. Need to highlight the word that is been searched, while displaying the result. These are the h

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 05:50

    You can do that by creating a pipe and applying that pipe to the summary part of array inside ngfor. Here is the code for Pipe:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
        name: 'highlight'
    })
    
    export class HighlightSearch implements PipeTransform {
    
        transform(value: any, args: any): any {
            if (!args) {return value;}
            var re = new RegExp(args, 'gi'); //'gi' for case insensitive and can use 'g' if you want the search to be case sensitive.
            return value.replace(re, "$&");
        }
    }
    

    and then in markup apply it on a string like this:

    Replace 'search' with the word you want to highlight.

    Hope this will help.

提交回复
热议问题