How to use Angular slice pipe in innerHTML?

Viewed 1355

I have a whatsNewDetail.content string which contains html elements:

<span style="font-family: &quot;Open Sans&quot;, Arial, sans-serif; font-size: 14px; text-align: justify;">In nec convallis justo. Quisque egestas mollis nibh non hendrerit. Phasellus tempus sapien in ultricies aliquet. Maecenas nec risus viverra tortor rhoncus venenatis in sit amet enim. Integer id ipsum non leo finibus sagittis in eu velit. Curabitur sed dolor dui. Mauris aliquam magna a ipsum tincidunt tempor vitae sit amet ante. Maecenas pellentesque augue vitae quam faucibus, vel convallis dolor placerat. Pellentesque semper justo a turpis euismod, ac gravida enim suscipit.</span>

Whenever I use the slice pipe, it doesn't display anything. I assume that the html elements is included in the slice.

 <span style="font-size: 13px" [innerHTML]="whatsNewDetail.content | slice:0:15+'...'></span>

What I want to achieve is the text to be sliced like:

In nec convalli...

not

<span style="fo...

How can I use the slice pipe after the text is rendered?

2 Answers

This is what I managed to do. I created a hidden element to hold the innerHTML and added a template reference variable named #whatsNew.

<p hidden [innerHTML]="whatsNewDetail.content" #whatsNew></p>

Then I created a function that returns the innerText of an element.

getInnerText(el) {
  return el.innerText;
}

After that I created the element with the slice pipe

<p class="article-content">{{ getInnerText(whatsNew).length > 150 ? (getInnerText(whatsNew) | slice:0:150) +'...' : getInnerText(whatsNew) }}</p>

One technique i can suggest is -

In Html File =>

<span style="font-size: 13px">
 <span style="font-family: &quot;Open Sans&quot;, Arial, sans-serif; font-size: 14px; text-align: justify;">{{whatsNewDetail.content.substring(0,15)}}...</span>
</span>

In Ts File =>

whatsNewDetail= {content: `In nec convallis justo. Quisque egestas mollis nibh non hendrerit. Phasellus tempus sapien in ultricies aliquet. Maecenas nec risus viverra tortor rhoncus venenatis in sit amet enim. Integer id ipsum non leo finibus sagittis in eu velit. Curabitur sed dolor dui. Mauris aliquam magna a ipsum tincidunt tempor vitae sit amet ante. Maecenas pellentesque augue vitae quam faucibus, vel convallis dolor placerat. Pellentesque semper justo a turpis euismod, ac gravida enim suscipit.`}

This should solve your problem.

Note: In case you meant to expand the text by clicking on the ... use a seperate span for '...' alone and use ngif to expand and contract the span with the text stored in whatsNewDetail.content

Related