0

I get a string from my back-end and when I display it, < br/> appears like text.

I'd like to convert them to real HTML tag or replace it by a real break line.

Here's the string retrieved from the back-end:

Description from backend Description from <br/> backend Description
from backend Description from backend <br/>Description <br/>from <br/>
backend Description from backend <br/> Description from backend
Description from backend Description from backend

Here's my function:

ngOnInit(): void {
    this.uns = this.sentence$.subscribe(res => {
        this.sentence = res;
        if (this.sentence && this.sentence.length > 0) {
            this.sentence = res.replace('<br/>', '\n');
        }
    });
}
Dale K
  • 25,246
  • 15
  • 42
  • 71
Stev0x
  • 52
  • 11

3 Answers3

0

Where are you displaying it? If it's inside a text area or input then you need to replace the <br> with new line, if it's inside a div you don't have to do it. To replace the <br> you need to do:

this.sentence = res.split("<br>").join("\n")
Specy
  • 189
  • 2
  • 13
  • Thanks for your quick response Specy :) ! I just display it in angular component (html) like this:

    {{sentence}}

    I tried what you told me but it doesn't work. The text is displayed only without the < br>
    – Stev0x Jun 03 '20 at 10:18
  • I don't know, I have never used angular so I can't say. Wait for someone to answer – Specy Jun 03 '20 at 10:20
  • It works when i log it but doesn't work in the template – Stev0x Jun 03 '20 at 10:20
  • Thanks four your help :) – Stev0x Jun 03 '20 at 10:20
  • Look here :https://stackoverflow.com/questions/14963444/angularjs-is-rendering-br-as-text-not-as-a-newline – Specy Jun 03 '20 at 10:21
0

HTML won't print your white space characters just because you have them, it will just print the first space and then skip the rest.

You can user a <pre></pre> tag to fix that and then you can use something like sentence = sentence.split("<br>").join("\n") to fix the <br/> issue.

Dale K
  • 25,246
  • 15
  • 42
  • 71
Massaynus
  • 322
  • 2
  • 9
0

I found the best solution:

I just have to add Angular directive ([innerHtml] to format the text and interpret html tag.

Like this:

<p [innerHTML]="sentence$ | async"></p>
Stev0x
  • 52
  • 11