Highlight the search text - angular 2

ngx-text-highlight example
angular 4 highlight text in textarea
angular highlight text input
highlight text in angular 8
how to create highlight text with same text when we type in search box in angular
text annotation angular
angular bold part of text
angular 4 directive highlight text

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 html and component that is been used.


 <div *ngFor = "let result of resultArray">
<div>Id : result.id </div>
<div>Summary : result.summary </div>
<div> Link : result.link </div>


resultArray : any = [{"id":"1","summary":"These are the results for the searched text","link":"http://www.example.com"}]

This resultArray is fetched from hitting the backend service by sending the search text as input. Based on the search text, the result is fetched. Need to highlight the searched text, similar to google search. Please find the screenshot,

If I search for the word "member", the occurence of the word "member" gets highlighted. How to achieve the same using angular 2. Please suggest an idea on this.

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';

    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.

Angular2 text highlight pipe � GitHub, Pipe} from 'angular2/core';. @Pipe({ name: 'highlight' }). export class HighLightPipe implements PipeTransform {. transform(text: string, [search]): string {. Highlight the search text - angular 2. 392. July 07, 2017, at 10:14 AM. A messenger displays the search results based on the input given by the user. Need to

The selected answer has the following issues:

  1. It will return undefined if there is nothing provided in the search string
  2. The search should be case insensitive but that should not replace the original string case.

i would suggest the following code instead

transform(value: string, args: string): any {
    if (args && value) {
        let startIndex = value.toLowerCase().indexOf(args.toLowerCase());
        if (startIndex != -1) {
            let endLength = args.length;
            let matchingString = value.substr(startIndex, endLength);
            return value.replace(matchingString, "<mark>" + matchingString + "</mark>");

    return value;

How to highlight the search text in Angular 6, import {PipeTransform, Pipe} from 'angular2/core';. @Pipe({ name: 'highlight' }). export class HighLightPipe implements PipeTransform {. transform(text: string� Highlighting search result improves the user experience and makes the search process less time consuming compare to showing the search result only. We are very familiar with this feature, it is available in almost every browser, rich text editors and document processor like Google docs.

One difficulty the innerHTML method has is in styling the <mark> tag. Another method is to place this in a component, allowing for much more options in styling.


<mark *ngIf="matched">{{matched}}</mark>{{unmatched}}


import { Component, Input, OnChanges, OnInit } from "@angular/core";

    selector: "highlighted-text",
    templateUrl: "./highlighted-text.component.html",
    styleUrls: ["./highlighted-text.component.css"]
export class HighlightedTextComponent implements OnChanges {
    @Input() needle: String;
    @Input() haystack: String;
    public matched;
    public unmatched;

    ngOnChanges(changes) {

    match() {
        this.matched = undefined;
        this.unmatched = this.haystack;
        if (this.needle && this.haystack) {
            const needle = String(this.needle);
            const haystack = String(this.haystack);
            const startIndex = haystack.toLowerCase().indexOf(needle.toLowerCase());
            if (startIndex !== -1) {
                const endLength = needle.length;
                this.matched = haystack.substr(startIndex, endLength);
                this.unmatched = haystack.substr(needle.length);


mark {
    display: inline;
    margin: 0;
    padding: 0;       
    font-weight: 600;


<highlighted-text [needle]=searchInput [haystack]=value></highlighted-text>

Highlight Text Within a String Using Angular and Regular , Highlight Text Within a String Using Angular and Regular Expressions is out. A sequence of characters that forms a search pattern, mainly for use in has experience in Android, Node.js, Apache Cordova, Java, NoSQL,� Highlight Search Results in ng repeat using AngularJS: Let us see how to highlight the search results in ng repeat using Angular filter. Highlighting the search result improves user experience and minimizes the search time when compared showing the search results. Here is the process that explains how to highlight the strings in ng repeat data:

Building on a previous answer (HighlightedText-Component) I ended up with this:

import { Component, Input, OnChanges } from "@angular/core";

    selector: 'highlighted-text',
    template: `
        <ng-container *ngFor="let match of result">
            <mark *ngIf="(match === needle); else nomatch">{{match}}</mark>
            <ng-template #nomatch>{{match}}</ng-template>
export class HighlightedTextComponent implements OnChanges {
    @Input() needle: string;
    @Input() haystack: string;
    public result: string[];

    ngOnChanges() {
        const regEx = new RegExp('(' + this.needle + ')', 'i');
        this.result = this.haystack.split(regEx);

This way also multiple matches of the needle are highlighted. The usage of this component is similar to the one in the previous answer:

<highlighted-text [needle]="searchInput" [haystack]="value"></highlighted-text>

For me this approach using a component feels more secure, since I do not have to use "innerHtml".

ngx-text-highlight, Installation Angular Text highlight Directive ==== ngx-text-highlight. 0.1.6 • Public • Published 2 years ago. Readme � ExploreBETA � 0Dependencies� Get the Highlighted/Selected text using Angular 2. NodeJS PhoneGap Pinterest Plugin ReactJS Reddit Responsive REST Retail SASS Scroll Search SQL Startup Testing

If you have multiple words in your string than use pipe which accepts array and highlight each word in result.

You can use following pipe for multiple search words:-

import { Pipe, PipeTransform } from '@angular/core';

    name: 'highlight'

export class HighlightText implements PipeTransform {

    transform(value: any, args: any): any {
        if (!args) {return value;}
        for(const text of args) {
            var reText = new RegExp(text, 'gi');
            value = value.replace(reText, "<mark>" + text + "</mark>");
            //for your custom css
            // value = value.replace(reText, "<span class='highlight-search-text'>" + text + "</span>"); 

        return value;

Split you string to generate array of strings.

var searchTerms = searchKey.split(' ');


<div [innerHTML]="result | highlight:searchTerms"></div>

If you wanted to use custom class :

.highlight-search-text {
  color: black;
  font-weight: 600;

All the best!

Filter the data and highlight the filtered/searched result using Pipe in , <head> <base href="." /> <script type="text/javascript" charset="utf-8"> window. 2. Highlighting the search result using Angular2 Pipe. For More details visit� Things have changed between AngularJS and Angular, but the topic is still very valuable. Being able to manipulate HTML on the fly can solve many problems in Angular. We're going to see how to highlight text within HTML using a query string and simple replace logic. The logic behind what we're building is as follows:

Highlight search result using Angular filter, <script src="app.js"></script> <style> .highlighted { background: yellow } </style> </head> <body ng-app="Demo"> <h1>Highlight text using AngularJS.</h1> 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.

TextHighlight Directive, Use the search box to search for a certain string in this text. All the results will be highlighted in the same color� In angular 2 we don't have pre-defined filter and order by as it was with AngularJs, we need to create it for our requirements. It is time killing but we need to do it, (see No FilterPipe or OrderByPipe). In this article we are going to see how we can create filter called pipe in angular 2 and sorting feature called Order By.

angular-highlight-pipe, Toggle light/dark theme. Toggle Zen Mode. Project. Download Project. Info. Starter project for Angular apps that exports to the Angular CLI. 3.7k. 42. Files. src . This seems to be the top link in Google, so here's an improved version for Angular 2.0 final. The original version had a problem with capitalized characters, replacing them with their lower case equivalent and also didn't escape regex control chars, resulting in other bugs.

  • I found this gist working perfectly
  • This also replaces the found substring with the searched one, applying the wrong case.
  • Clear and simple answer!
  • @afe return value.replace(new RegExp(args, 'gi'), "<mark>$&</mark>"); Will replace with the same case
  • Searching for . will select everything, and searching for nothing will create mark for every character (for this is easy, a simple if (!args) {return value;} at the beginning of the function)
  • @Jeremy Added that. Thanks for the input.
  • This did not match multiple occurrences of the word but it did provide a good point about trying to keep the search from obliterating the by overriding the casing. I submitted an answer that used case sensitive regex to attempt to address the problem. And falls back to case-insensitive when the search is funky.
  • It should be [innerHTML] not [innetHTML]
  • Tip: If you change "<mark>" + text + "</mark>" to "<mark>$&</mark>" it will preserve casing of the highlighted section.