【问题标题】:How to truncate HTML content in Angular 2?如何在 Angular 2 中截断 HTML 内容?
【发布时间】:2018-01-01 05:31:33
【问题描述】:

我用一根管道截断,正常文本工作正常,但不是 html 内容

app.html

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

【问题讨论】:

  • 什么是howtoreach
  • @Maximus HTML 内容,Qn 更新
  • 没有,怎么在模板中获取呢?
  • 如果howtoreach.content 是一个HTML 字符串,那么截断它就不会很好地工作。它可能会在标签中间截断它。在任何情况下,您都需要使用 [innerHTML] 插入它
  • 还有什么方法可以让它动态对齐?

标签: angular


【解决方案1】:

我遇到了同样的问题,并意识到使用innerHTML 很难找到 Angular 2 解决方案。

我的解决方案

你可以像这样创建一个自定义函数:

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;
}

然后在你看来:

&lt;div [innerHTML]="truncateHTML(html_string)"&gt;&lt;/div&gt;

应该可以的。


最后评论

我正在使用innerHTML,因为还有一堆未格式化的字符,例如:

&oslash; &aelig; &nbsp;

特别是如果你来自北欧国家,拥有 æ、ø 和 å :)



正则表达式来自:StripHTML post


更新

在替换 HTML 之前,我必须替换断点 &lt;br /&gt;,因此行尾的单词(在换行符之前)和下一个(行上的第一个单词)在显示时在它们之间有空格:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2014-10-20
    • 2017-03-23
    • 1970-01-01
    相关资源
    最近更新 更多