1

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?

1
  • did you check my answer? Commented Jul 4, 2018 at 15:06

3 Answers 3

1

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>`;
Sign up to request clarification or add additional context in comments.

Comments

0

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?

Comments

0

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.

1 Comment

I like the idea of simplifying string expression, but this still does not apply/update the view with new style. However, I now found the answer. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.