Safaa Hammoud
2 min readDec 6, 2020

How to insert break line within a string in Angular

Photo by Lubo Minar on Unsplash

In this article, you will learn 3 ways of adding break line to string interpolation in Angular 2+.

The first way is by using CSS

You can simply add styling property white-space: pre-wrap to the div surrounding your string, where it breaks the line at new line character in the string and renders the white spaces as it is.

Example:

<div style="white-space:pre-wrap">{{withBreaksHtml}}</div>

Note : break line character ,breaks line in HTML text document and it does not work in string variable declared in typescript file, unless you use step 2 or 3 below.

The second way is by using HTML binding in Angular

You can use “inner Html” property binding to interpolate an HTML snippet into an HTML element, by that Angular handles any XSS vulnerabilities by sanitizing the unsafe content in the HTML snippet and keeping the safe content to be rendered.

Example:

<div [innerHtml]="withBreaksHtml"></div>

The third way is by using pipe

I used View Children to access the DOM of the div elements rendering the description of the accordion item and to differentiate between DOM div elements I added to the div an id.

I used template reference variable instead of id to access the element data within DOM , while id purpose is to give unique identifier .

Example:

Step 1:

Add a class that will act as a pipe and take reference of child element and set its inner HTML to its value, in this way break line will work in template

Steps 2:

In the typescript file, I wanted to create a unique view child element but there wasn’t an option to do so unless by adding a unique id to the div in HTML and use view children in the typescript file to loop over each div and access its id, then set the inner HTML of the div with its respective value.

Step 3:

You can find the full code in a project on my Github — click me.

Conclusion

By now you have learned the three ways of adding break line characters, each way depends on the case you are handling, one by HTML, the other is by CSS, and lastly by Angular pipe

Productive Tip

When working with an Angular project or using Webpack dev server in your project and you pressing ctrl s ,the whole project is going to be recompiled so to save time in compilation, enable Hot Module Replacement when you serve your project.