简体   繁体   中英

Highlighting a specific text which in html raw text

What I'm trying to accomplish is highlight a text that given by parameter inside a raw text which format is HTML.

I'm working with Angular 7 and tried to do that jQuery functions and some third party libs but did not do that yet.

Here the scenario;

raw HTML text comes as below

<div #rawContentContext class="form-group m-form__group row col-lg-12" style="width:100%; height: 100vh; overflow:scroll;">
  {{ getHtmlRawContent() }} 
</div>

getHtmlRawContent() method returns HTML raw code as string

I've tried to handle this issue with markjs and hilitorjs but it didn't work because they're trying to solve this by replacing keyword with <mark> keyword so the text already raw HTML so those steps were not work.

Here approach and code example;

<script type="text/javascript">
   var myHilitor = new Hilitor(document.getElementById("rawContentContext"));
   myHilitor.apply("exceeded");
</script>

It actually works some scenarios which rendering HTML code rather than outputting as raw.

Also tried with 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;}
        if (value!=null){
            var re = new RegExp(args, 'gi');
            return value.replace(re, '<p style="background-color: red;"> <mark>$&></mark> </p>');
        }

    }
}

And HTML side

{{ getHtmlRawContent() | highlight:getSearchedKeyWord() }}

Thank you.

You're almost there, but in Angular, code between double braces {{<code>}} will be rendered as escaped html text (plain text). In order to your string be rendered as html, it must be in the attribute innerHTML of your parent element, like this:

<div #rawContentContext class="form-group m-form__group row col-lg-12"
    style="width:100%; height: 100vh; overflow:scroll;"
    [innerHTML]="getHtmlRawContent() | highlight:getSearchedKeyWord()">
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM