使用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 <a href="http://www.ign.com/articles/2017/11/30/marvels-the-avengers-infinity-war-trailer-breakdown"> what comes next.</a>
当我检查身体的输出时,我看到了:
<p _ngcontent-c1 style="margin-bottom: 2rem; white-space: pre-wrap;">I already can’t wait to see <a href="http://www.ign.com/articles/2017/11/30/marvels-the-avengers-infinity-war-trailer-breakdown">what comes next.</a></p>
。
如何更改HTML以使字符串能够正确使用链接和图像?
答案 0 :(得分:0)
嘿伙计们,我不知道你为什么拒绝投票给我答案,但这里有解决你问题的方法:
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 {}
您可以为此应用程序编写管道,如本文所述:
答案 1 :(得分:0)
将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>