Evgeny Lukiyanov
Evgeny Lukiyanov

Reputation: 488

Angular2 highlight a number of words in html string with javascript

In my Angular2 component, I receive a string from the parent component, that contains some HTML and it is being injected into the view. This part works! I now want to highlight a number of first words in that html (note: that number changes every time, let's say 15 for now).

Code:

1) html string (content) contains somethink like this:

<p>Hello, this is a <span> smaple text</span></p>
<p>More things to say here...</p>
<p>Perhaps an image as well here, or a link: <a> This is a link here</a></p>
<p>This is very long, did you read this?</p>

2) In Angular2 this string is injected into the component:

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

   <button type="submit" (click)="toggle()" >Toggle Highlight</button>

3) When toggle btn is clicked: the plan is to count 15(or whats specified) words in the html string, and inject a span(with green background) from start to word #15..

Right now, I am currently trying to simply inject a span with a green background colour around the whole html, like this:

toggle() {
    this.content = "<span style=\"background-color: green;\">"+ this.content +"</span>";
  }

Even this is not working, I also tried with a class, but it's not being picked up. And there is another problem with inserting a span into this html as word 15 may be in a different tag which will cause problems.

Any suggestion if there is another way to highlight a number of words in string of html?

Upvotes: 1

Views: 292

Answers (3)

Evgeny Lukiyanov
Evgeny Lukiyanov

Reputation: 488

It seems the correct way of doing it is not using:

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

As innerHTML won't support any hardcoded styles in tags.

Instead in html use:

<div #dataContainer></div>

And then in Angular TS:

this.dataContainer.nativeElement.innerHTML =  `<div style="background-color: rgba(0, 210, 0, 0.45);">${this.content}</span>`;

Upvotes: 1

Anshuman Jaiswal
Anshuman Jaiswal

Reputation: 5462

Rather than span use div to set highlighted background color as:

toggle() {
  this.content = `<div style="background-color: green;">${this.content}</span>`;
}

Also you can use back tick (`) to simplify the string expression.

Upvotes: 0

Taranjit Kang
Taranjit Kang

Reputation: 2580

I think the best approach for this would probably be a directive or a pipe. Basically add directive to the component, check the length and then add the class to the element ref.

something similar to this:

Angular 2/4 : How to check length of input's value using directive?

Upvotes: 0

Related Questions