问题描述
我正在尝试创建一个输出原始html的Angular2自定义管道.我希望它只是将输入中的换行符转换为HTML换行符.如何从angular2管道输出原始HTML?
I'm trying to create an Angular2 custom pipe that outputs raw html. I want it to simply convert newlines in the input into HTML line breaks. How do I output raw HTML from an angular2 pipe?
以下是我当前的管道定义,但是它转义了我不需要的HTML:
The following is my current pipe definition, but it escapes the HTML which I don't want:
import {Pipe, PipeTransform} from '@angular/core';
/*
* Converts newlines into html breaks
*/
@Pipe({ name: 'newline' })
export class NewlinePipe implements PipeTransform {
transform(value: string, args: string[]): any {
return value.replace(/(?:\r\n|\r|\n)/g, '<br />');
}
}
只需快速注释一下,因为这个问题似乎得到了很多意见和建议,尽管对于我的特定示例,用例css可能会是一个更好的选择,但我将保留我的已接受答案.实际上是我更改的内容.但是我的实际问题是我如何从一个有角度的2管道输出原始html",而不是什么是呈现换行符的最佳方法",这就是公认的答案.
Just a quick note since this question seems to get a number of views and activity that I'm leaving my accepted answer as is, even though for my specific example use-case css probably would have been a better option and was in fact what I changed to. But my actual question was "how do I output raw html from an angular 2 pipe", not "what's the best way to render line breaks" which is what the accepted answer shows.
但是请注意,如下面的评论中所述,如果您确实在接受的答案中使用该方法,则需要确保您未呈现未经检查的用户输入,因为这可能会使您面临XSS漏洞.
Beware though, as mentioned in comments below, if you do use the method in the accepted answer you need to ensure that you're not rendering unchecked user input as this could open you up to XSS vulnerabilities.
推荐答案
答案(我在发布问题后才发现)不是更改管道定义中的任何内容,而是在使用管道时绑定到[innerHtml]
The answer (I found just after posting the question) is not to change anything in the pipe definition, but instead to bind to [innerHtml] when using the pipe.
所以替换掉它:
<div class="panel-body">
{{mycontent | newline}}
</div>
与此:
<div class="panel-body" [innerHtml]="myContent | newline">
</div>
如果在管道定义中有办法做到这一点,那就太好了……
It would be nice if there were way to do this in the pipe definition though...
请注意,因为这个答案似乎吸引了许多反对意见,我将按原样保留它,尽管对于我的特定示例,用例css可能会是一个更好的选择,实际上,这是什么呢?我改用了.
Just a quick note since this answer seems to attract a number of downvotes that I'm leaving it as is, even though for my specific example use-case css probably would have been a better option and was in fact what I changed to use.
但是我的实际问题是如何从有角度的2管道输出原始html",而不是呈现换行符的最佳方法是什么".该答案显示了如何执行此操作.
BUT my actual question was "how do I output raw html from an angular 2 pipe", not "what's the best way to render line breaks." This answer shows how to do this.
但是,请注意,如下面的评论中所述,如果您确实在此答案中使用该方法,则需要确保您未呈现未经检查的用户输入,因为这可能会使您面临XSS漏洞.
BEWARE though, as mentioned in comments below, if you do use the method in this answer you need to ensure that you're not rendering unchecked user input as this could open you up to XSS vulnerabilities.
这篇关于Angular2管道:输出原始HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!