If you've got a string that includes new line characters (\n) and carriage return characters (\r) and you try to print them on a UI via Angular, you might be disheartened when you see the results.

That's because Angular, by default, will print the actual character combinations: \n and \r.

But who the heck wants that?

Certainly not you or you wouldn't have found this article via a search engine.

So I'll show you how to print out the new lines and carriage returns instead of their respective notations in code.

Another Innie

You might know about the innerHTML property if you've been doing client-side work for a while. But do you know about innerText?

Yep, that one exists, too.

And that's what you need to use here.

So if you've got a string with a bunch of linefeeds and carriage returns, you might try spitting it out on the screen with code like this:


Well, that ain't gonna cut it. You'll just get exactly what you don't want.

So try this instead:

<mat-card-content [innerText]="email.plainText"></mat-card-content>

Ah. That's going to give you the desired result.

You'll go from new line and carriage return codes to actual new lines and carriage returns.

It's all handled with the magic of the innerText binding property you see there. In this case, innerText is the binding target and email.plainText is the binding source.

Keep in mind that email.plainText must already be defined in the component related to the HTML where you use the innerText binding property. Otherwise, you'll get an error.

For my part, email represents an email message and the plainText property is the plain text version of the email as received from the Gmail API. That string includes a bunch of carriage return and new line codes.

So I use something like the code above to display the corresponding whitespace.

You can, too.

Wrapping It Up

There you have it. An easy way to print new lines and carriage returns as they were meant to be printed on the UI.

Now take what you've learned here and build a great application with it.

Have fun!