Angular: how to render line breaks in a string inside curly braces?

Viewed 1661

Maybe this is not possible but I wonder if I can embed a line break in a string I pass to MatDialogComponent displayed on a form via {{ }}

I designed a simple WarningDialogComponent that has params for title, message, OK and cancel button text.

The message text is displayed inside the template

<mat-dialog-content>
    {{message}}
</mat-dialog-content>

This works fine except if I want the message to be have defined line breaks, something like:

You are about to delete account 'Electricians'

This cannot be undone!

I tried using backtic quotes, or \n\n embedded in message and I know html is normally escaped. Of course I could redesign my form, or instruct it to render embedded html, but was hoping there is a simple way to somehow put a line break in the string contained in the message variable that would work without a having to tinker with the component itself.

3 Answers

You could do some css stuff. mat-dialog-content element automatically gets the mat-dialog-content class. Simply add this style to this class in your global stylesheet

.mat-dialog-content{white-space:pre;}

Now your \n shall be considered as new line in your plain text. Please refer this simple stackblitz.

Thanks.

it sounds like what you are looking to do is embed html in your variable and have angular display that html without sanitizing it. so that your your {{message}} could have line breaks <br/> and have them rendered in the message.

by default Angular sanitizes the contents of variables to prevent cross site scripting.

however, if the value you wish to display is 'trusted' (i.e. it isn't one that a user can enter), angular allows you to use the Dom sanitizer to mark content as safe.

by using this you can have your message contain HTML and have it rendered as you would expect. however, for anything that you are looking to bypass the Angular sanitizer with, be sure you control where that message is coming from

It seems you could use innerHTML property instead curly braces. Then you can use the tag <br/>

<mat-dialog-content [innerHTML]="message"></mat-dialog-content>
Related