JSkyS
JSkyS

Reputation: 443

Why are my <br> tags showing in my browser display for angular project

I have text that is being saved from a textarea. I save it to the database. I now want to display this text onto another page after submit. I would like to keep the same format as the original text input.

This is what shows up on the browser after redirecting to the other page. Im replacing br with --- or else it will create actual breaks in this text. --- equals br

"M <---><---/> O <---/><---/>C<---/>Hub<---/>"

How do I display onto the page without the br tags? I have seen this work in other circumstances but unsure what I am doing wrong.

I have been able to use the .replace method to replace the enter's with
. The only thing though, the
tag is showing up in the display.

x.component.ts

  getMessages() {
    this._messageBoardService.getMessages().subscribe(
      (data: any) => {
        this.msgList = data
        this.msgList[0].message = this.msgList[0].message.replace(/\n/g, "<br />")
      })

  }

x.component.html

<h3>{{ msgList[0].title }}</h3>
<p> {{ msgList[0].message }}</p>

The expected output without the breakpoints is

M

O

C Hub

Upvotes: 1

Views: 3926

Answers (2)

Vova Bilyachat
Vova Bilyachat

Reputation: 19474

Because this is how angular works. It prevents from injection "bad html". To print html you will need to use DomSanitizer

Change your code

this.msgList[0].message = this.msgList[0].message.replace(/\n/g, "<br />")

to

 this.msgList[0].message =  sanitizer.bypassSecurityTrustHtml(this.msgList[0].message.replace(/\n/g, "<br />"))

then template

<p [innerHTML]="msgList[0].message"></p>

BUT for security reason I would not do it I'd better do it with css

p.break-newline{
  white-space: pre-wrap
}

add class

<p class="break-newline"> {{ msgList[0].message }}</p>

And now you dont need to modify your message in code.

Upvotes: 3

Joy Biswas
Joy Biswas

Reputation: 6527

If it is just for display purposes add a css property that displays your line breaks

<p class="message">{{ msgList[0].message }}</p>
.message { white-space: pre-line; }

in which case your api fetching has no operations

getMessages() {
    this._messageBoardService.getMessages().subscribe(
      (data: any) => {
        this.msgList = data
      })
  }

OR

else you can do in angular is use innerHTML property

<p [innerHTML]="msgList[0].message"></p>

Upvotes: 2

Related Questions