How to highlight searched text in angular6, using pipe?

Raj picture Raj · Sep 29, 2018 · Viewed 8k times · Source

I want to build a search box in angular, that would return the array of item,and also highlight the searcchedTerm in the results array.

For example: In Chrome if you are searching any text, it would highlight with light yellow background. Similar to that.

enter image description here

I have created two pipes, one to filter the result and another to highlight the term in the results which is searched. But i am getting error replace is not a function.

And also, can the two pipes be merged into one?

highlight.pipe.ts

transform(list: any, searchText: string): any[] {
    if (!list) { return []; }
    if (!searchText) { return list; }

    const re = new RegExp(searchText, 'gi');
    const value = list.replace(re, "<span class='yellow'>" + searchText + "</span>" );
    return list;
}

using the pipe in template

<div class="card" *ngFor="let item of list | search: searchedTerm | highlight: searchedTerm">

Answer

Enas Osama picture Enas Osama · Sep 29, 2018

1- In the highlight.pipe.ts

transform(list: any, searchText: string): any[] {
console.log('lists', list);
console.log('searchText', searchText);

if (!list) { return []; }
//to remove highlighted tags before any processing
list = list.map(function (item) {
  item.name = item.name ? String(item.name).replace(/<[^>]+>/gm, '') : '';
  return item;
})
if (!searchText) { return list; }

const re = new RegExp(searchText, 'gi');
const value = list
  .map(function (item) {
    //this will match the values and add the highlight tag for it
    item.name = item.name.replace(re, "<span class='yellow'>" + searchText + "</span>");
    return item
  });
return value;

}

2- Move the .yellow style to style.css to match for the injected html

3- In the app.component.html

<div class="card" *ngFor="let item of list | search: searchedTerm | highlight: searchedTerm">
 <span [innerHTML]="item.name"></span>
</div>

If you want the items to disappear then use the search pipe if you only want it highlighted then the highlight pipe alone is enough

a link for the updated Stackblitz : https://stackblitz.com/edit/angular-searchpipe?file=src%2Fapp%2Fapp.component.html