[Fixed] Add line breaks inside property to be displayed within <p> tags in the template angular

Issue

I have a property errorMessage declared in my ts component. I need to store a string within this that contains multiple lines that need to be separated by a line. ‘\n’ doesn’t seem to work with this. Please suggest the way to do this.

In ts component:

this.errorMessage = 'An error has been encountered. \nDetails:\n' + errorString;

In html template:

<p>{{errorMessage}}</p>

Solution

You can do the one trick here as you can use [innerHTML] attribute to show you html that is inside your errorMessage

You have to modify your code in component like

this.errorMessage = 'An error has been encountered. <br>Details:' + errorString;

And in your template you can render you above message by using above attribute like

<p [innerHTML]="errorMessage"></p>

The above code will render your errorMessage as a HTML not a string so line break will also rendered

Leave a Reply

(*) Required, Your email will not be published