Angular2 Pipes: output raw HTML

后端 未结 9 2080
春和景丽
春和景丽 2020-12-13 17:43

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 a

9条回答
  •  感情败类
    2020-12-13 18:09

    Here's my take on it, using a simple pipe

    make a file called nl2pbr.pipe (which stands for: new line to p / br) and put it inside pipes folder, and this is its content:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'nl2pbr'
    })
    export class Nl2pbrPipe implements PipeTransform {
    
      transform(value: any, args?: any): any {
        // return value.replace(/\n/g, '
    '); value = value.replace(/(?:\r\n\r\n|\r\r|\n\n)/g, '

    '); return '

    ' + value.replace(/(?:\r\n|\r|\n)/g, '
    ') + '

    '; } /**************************** * example useage *
    ****************************/ }

    Make sure you add the pipe to app.module:

    import { Nl2pbrPipe } from './pipes/`nl2pbr.pipe`';
    

    and Nl2pbrPipe to the declarations: []

    Usage example:

    will output:

    hello

    this is a new paragraph
    and a new line

提交回复
热议问题