Keep line breaks in HTML string

I had a similar situation where I had HTML code like this:

<div>{{msgTitle}}</div>

And I tried putting both '\r\n' and &lt;br&gt; in the string msgTitle, but neither of them worked to put a newline in the text displayed on the page. This link gave me the solution:

https://github.com/angular/angular/issues/7781

Use [innerHTML]="msgTitle" instead of {{msgTitle}}.


HTML, in general, uses br tags to denote a new line. A plain textarea tag does not use this, it uses whatever the user's system uses to denote a new line. This can vary by operating system.

Your simplest solution is to use CSS

<main role="main" class="container">
  <p style="margin-bottom: 2rem;white-space:pre-wrap;">{{review.body}}</p>
</main>

This will maintain any "white space" formatting, including additional spaces.

If you want to actually replace the newline characters with br tags you can use the following regex

<main role="main" class="container">
  <p style="margin-bottom: 2rem;" [innerHTML]="review.body.replace(/(?:\r\n|\r|\n)/g, '<br>')"></p>
</main>

Edit Thanks to ConnorsFan for the heads up on replace not working with interpolation.


by using the [innerText] directive the white spaces seem to be maintained, as well as the \n new lines

e.g. <small style="display:block" [innerText]="review.body"></small>