abyrne85
abyrne85

Reputation: 1460

innerHtml not working in angular 5

I am trying to display a json string which contains line breaks and line returns; \r and \n

This is the json:

 {
   "Content": "OFCH\r\nPVC Double Glazed Windows\r\nMains Services"
 }

This is the HTML:

<p class="PropertyBrochure__DescriptionContent" [innerHTML]="description.Content"></p>

This is the output:

OFCH PVC Double Glazed Windows Mains Services

As you can see the \r\n in the json string are stripped and ignored. Am I missing something?

Upvotes: 1

Views: 1343

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97282

The carriage returns are neither stripped nor ignored. The HTML will be resolved by Angular as:

<p class="PropertyBrochure__DescriptionContent">OFCH
PVC Double Glazed Windows
Mains Services</p>

The problem is that the browser's HTML renderer collapses the white-space and expects you to use <br> elements to force new lines.

Alternatively, you can control the browser's handling of white-space using CSS (see documentation here):

.PropertyBrochure__DescriptionContent { white-space: pre; }
<p class="PropertyBrochure__DescriptionContent">OFCH
PVC Double Glazed Windows
Mains Services</p>

Upvotes: 5

Related Questions