【问题标题】:Insert HTML into string将 HTML 插入字符串
【发布时间】:2018-03-13 21:15:02
【问题描述】:

使用 Angular 5 和 Firebase,我创建了一个评论网站,允许用户在 CreateComponent 上创建评论并在 ReviewComponent 上阅读它们。我希望评论的正文能够包含链接或图像的 HTML。

ReviewComponent 提取评论正文:

<p style="margin-bottom: 2rem; white-space: pre-wrap;">{{review.body}}</p>

我正在使用pre-wrap 来维护正文的换行符。

CreateComponent 的示例输入是:

I already can’t wait to see &lt;a href="http://www.ign.com/articles/2017/11/30/marvels-the-avengers-infinity-war-trailer-breakdown"&gt; what comes next.&lt;/a&gt;

当我检查身体的输出时,我看到了这个:

&lt;p _ngcontent-c1 style="margin-bottom: 2rem; white-space: pre-wrap;"&gt;I already can’t wait to see &amp;lt;a href="http://www.ign.com/articles/2017/11/30/marvels-the-avengers-infinity-war-trailer-breakdown"&amp;gt;what comes next.&amp;lt;/a&amp;gt;&lt;/p&gt;.

如何更改 HTML 以使字符串能够正确处理链接和图像?

【问题讨论】:

  • 我认为您需要使用富文本编辑器。

标签: html firebase angular5


【解决方案1】:

嘿伙计们,我不知道你为什么不赞成我的回答,但这里有解决你问题的方法:

https://plnkr.co/edit/VHvVpvnTeoGWsA0d3eex?p=preview

代码如下:

//our root app component
import {Component, NgModule, VERSION, Pipe, PipeTransform, ChangeDetectorRef } from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `
    <div [outerHTML]='selectedValue | html'></div>
  `,
})
export class App {
  selectedValue: string = 'I already can’t wait to see <a href="https://www.ign.com/articles/2017/11/30/marvels-the-avengers-infinity-war-trailer-breakdown"> what comes next.</a>';
  constructor(private cd: ChangeDetectorRef) {
  }
}


@Pipe({
  name: 'html'
})
export class HtmlPipe implements PipeTransform {

  transform(value: string) {
      return `<div>${value}</div>`;
  }

}

@NgModule({
  imports: [ BrowserModule, FormsModule ],
  declarations: [ App, HtmlPipe ],
  bootstrap: [ App ]
})
export class AppModule {}

您可以为此应用程序编写管道,如本文所示:

How to allow html in return of angular2 pipe

【讨论】:

    【解决方案2】:

    review.body 绑定到[innerHTML] 更正了此问题。

    <p style="margin-bottom: 2rem; white-space: pre-wrap;">{{review.body}}</p>
    

    现在

    <p style="margin-bottom: 2rem; white-space: pre-wrap;" [innerHTML]="review.body"></p>
    

    【讨论】:

      猜你喜欢
      • 2022-01-02
      • 2021-03-13
      • 2015-09-22
      • 1970-01-01
      • 2019-01-20
      • 2014-11-11
      • 1970-01-01
      • 2016-11-11
      • 2015-02-02
      相关资源
      最近更新 更多