Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
900 views
in Technique[技术] by (71.8m points)

angular - Angular2 Pipes: output raw 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?

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(/(?:
|
|
)/g, '<br />');
    }
}

EDIT: 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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could also use pure CSS

<span class="line-breaker">
{{text}}
</span>

.line-breaker {
  white-space: pre-line;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...