【问题标题】:String containing <br> doesn't break line with ngFor包含 <br> 的字符串不会与 ngFor 换行
【发布时间】:2019-12-24 15:27:12
【问题描述】:

我用 ngFor 遍历一个数组。该数组包含如下字符串:“Some Text 1 &lt;br&gt; some text 2”。这是 HTML:

&lt;div class="content" *ngFor="let item of graphService.contents"&gt;{{item}}&lt;/div&gt;

它会打印正确的文本,但不会换行。它像普通单词一样打印 br,但我希望它打破界限。如何在不将字符串分成两部分的情况下实现这一点,例如“Array.firstString + &lt;br&gt; + Array.secondString?

【问题讨论】:

标签: angular frontend


【解决方案1】:

你可以用这个

<div class="content" *ngFor="let item of graphService.contents">
    <div [innerHTML]="item"></div>
</div>

如果您想从富文本中呈现纯文本,则可以添加此功能。

this.utilService.htmlToPlaintext(content);

在你的服务中定义一个这样的函数htmlToPlaintext()

htmlToPlaintext(text) {
    var plain = text ? String(text).replace(/\\t/g, '') : '';
    return text ? String(plain).replace(/\\n/g, '') : '';
  }

【讨论】:

  • "Parser Error: Got interpolation ({{}}) where expression was expected" 是我尝试使用 [innerHTML] 时遇到的错误
  • 那你可以参考一下这个stackoverflow.com/questions/40203279/…
  • 通过提供 [innerHTML]="item" 尝试一次
  • 您的回答没有解决我的问题,但它引发的错误让我走上了正轨。
  • 是的,我错误地将值项绑定在双括号中。这就是问题所在。谢谢
【解决方案2】:

为了防止转义 HTML,你可以这样做:

    <div class="content" 
         *ngFor="let item of graphService.contents"
         [innerHTML]="item"></div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    • 2020-12-25
    • 1970-01-01
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多