28

I have a REST API with \n as backslash tags, can angular 6 replace these with <br> tags?

Here's my code:

{{x.deskripsi}}

I try to use this package, but I have no idea how to use it with binding inside a {{}} tag. I tried using

<p ng-bind-html="x.deskripsi | nl2br"></p>

but it doesn't work. Any help?
Thanks in advance.

Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
Shaugi
  • 419
  • 2
  • 8
  • 18

2 Answers2

90

You don't need a library. Simply set the white-space property of your tag to pre-wrap (or use a <pre> tag that should have this style by default)

document.querySelector('#formatted').innerText = 'Lorem\nIpsum';
#formatted {
  white-space: pre-wrap;
}
<div id="formatted"></div>
<div>Lorem\nIpsum</div>
22

You can use a pipe for the same:

import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'replaceLineBreaks'})
export class ReplaceLineBreaks implements PipeTransform {
transform(value: string): string {
      return value.replace(/\n/g, '<br/>');
   }
}

The pipe must be included in your @NgModule declarations to be included in the app. To show the HTML in your template you can use the binding innerHTML.

<p [innerHTML]="x.deskripsi | replaceLineBreaks"></p>
Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
Sanoj_V
  • 2,936
  • 1
  • 12
  • 28
  • thats work for inner html i try use this code `
    test html content\nnew line\nthird line' | ReplaceLineBreaks">
    ` its work correctly , but when i try with my binding data is not working, i try using `pure: false` still doesn't work any sugest ?
    – Shaugi May 15 '18 at 03:52
  • What type of data you binding on paragraph tag – Sanoj_V May 15 '18 at 03:59
  • I think paragraph tag does not contain any tags inside itself. Please see this link : `https://googleweblight.com/i?u=https://www.quackit.com/html/tags/html_p_tag.cfm&hl=en-IN`. – Sanoj_V May 15 '18 at 04:20
  • Not sure but some tags are not supported inside paragraph tags – Sanoj_V May 15 '18 at 04:40