2

I have used one pipe to truncate ,Working fine with normal text but not in html content

app.html

  <tr>
  <td>{{howtoreach?.content|truncate :40}}</td>  //html content.not working
  <td>{{howtoreach?.id}}</td>                   //Working
  <td>

howtoreach

1 Answers1

3

I had the same problem, and realised that it was difficult to find an Angular 2 solution with innerHTML.

My solution

You could create a custom function like this:

truncateHTML(text: string): string {

    let charlimit = 160;
    if(!text || text.length <= charlimit )
    {
        return text;
    }


  let without_html = text.replace(/<(?:.|\n)*?>/gm, '');
  let shortened = without_html.substring(0, charlimit) + "...";
  return shortened;
}

And then in your view:

<div [innerHTML]="truncateHTML(html_string)"></div>

That should work.


Last comment

I'm using innerHTML because there is still a bunch of unformatted characters like:

&oslash; &aelig; &nbsp;

Especially if you're from a nordic country with æ, ø and å :)



Regex is from: StripHTML post.


Update

I had to replace breaks <br /> before replacing HTML, so the word at the end of a line (before a line break) and the next (first word on line) had space in between them when shown:

let adding_spaces = text.replace(/<br \/>/g, "&nbsp;");
Community
  • 1
  • 1