[Fixed] How to return HTML expression from Angular method?

Issue

so the title is maybe not the best…but nothing better came to my mind:

I would like to highlight search keywords on the result list…this is the reason, why I am struggeling with this issue.
CSS:

highlightText{
 font-weight: bold;
}

In Typscript:

myVariable = "hello world";
keyword=" bonjour";

highlightText(text: string){
   return text.replace(keyword, "<span class='highlightStyle'>"+keyword+"</span>");
}

In HTML:

<div>
    {{highlightText(myVariable)}}
</div>

On the screen I see the whole text..:

< span class=’highlightStyle’ >bonjour< /span > world

However I would really expect:
bonjour world

yuhhuu that’s all 😀

any idea?

Thanks,Csaba

Solution

It’s better to use a pipe – it’s more performant (functions are run for each change detection cycle, while pipes only when their input arguments change)

check this out https://stackblitz.com/edit/angular-highlight-pipe

Leave a Reply

(*) Required, Your email will not be published