Sojimanatsu
Sojimanatsu

Reputation: 601

Highlight a word in text in Typescript by using HTML tag

I have been trying to use HTML tags inside Typescript to highlight particular words in a sentence before I put these sentence in HTML. I looked for several options in StackOverflow but I could not point to the solution.

The code example is:

example.sentences = this.sentences.filter((sentence: { Sentence: string | string[]; }) => sentence.Sentence.includes(word))
        .map((sentence: { Sentence: any; }) => sentence.Sentence.replace(new RegExp(word, 'gi'), match => {
          return `<mark class="marking">${match}</mark>`;
        }));

Then I am calling these sentences from HTML:

<mark *ngFor="let sentence of example.sentences">
      {{ sentence }}
</mark>

The result is:

Alice is in <mark class="marking">wonderland</mark> 

It looks like it is a text in the sentence but not rendered as HTML.

How can I define this in Typescript, or in HTML to change the colour of a word that is in a sentence?

Upvotes: 1

Views: 1940

Answers (3)

Delwyn Pinto
Delwyn Pinto

Reputation: 612

Use innerHTML to mark the HTML tags within a string. For example,

<div [innerHTML]="sentence"> </div>

Upvotes: 1

igg
igg

Reputation: 2250

You're already returning HTML in your example.sentences, I don't think that's necessary. Try it like this:

example.sentences = this.sentences.filter((sentence: { Sentence: string | string[]; }) => sentence.Sentence.includes(word))
        .map((sentence: { Sentence: any; }) => sentence.Sentence.replace(new RegExp(word, 'gi'), match => {
          return match;
        }));
<mark *ngFor="let sentence of example.sentences" [innerHTML]="sentence"></mark>

Upvotes: 1

VitoMakarevich
VitoMakarevich

Reputation: 455

Try to use

constructor(private sanitizer: DomSanitizer) {
// javascript: URLs are dangerous if attacker controlled.
// Angular sanitizes them in data binding, but you can
// explicitly tell Angular to trust this value:
this.dangerousHtml = `<mark class="marking">${match}</mark>`;
this.trustedHtml = sanitizer.bypassSecurityTrustHtml(this.dangerousHtml);

Upvotes: 0

Related Questions