Highlight the search text – angular 2

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, "<mark>$&</mark>");
    }
}

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

<div innerHTML="{{ str | highlight : 'search'}}"></div>

Replace ‘search’ with the word you want to highlight.

Hope this will help.

Leave a Comment