10

I have some html for an alert message box. Using interpolation, I can re-use the same html to show multiple different alert messages. It looks like this: <p>{{ myAlertMessage }}</p>

Now I want to show a longer alert message containing line breaks. However, I cannot seem to modify the interpolated component property (which is a string) in any way which will introduce line breaks.

For example, using </br>, or spacing the text across several lines in the component code (contained in either parentheses or back ticks), or the new line code (&#13;). None of these work to produce a line break in the text when the alert message is shown.

I would prefer not to have to add further property bindings just to cater for this particular use case.

Thanks in advance.

Brendan B
  • 369
  • 3
  • 19

4 Answers4

7

Just use

<span [innerHTML]="myAlertMessage"></span>

the innerHTML property will interpret your html code.

Alexandre N.
  • 2,594
  • 2
  • 28
  • 32
5

The solution, for Angular v2.1.1 at least, is to use [innerHTML]="myAlertMessage". It isn't necessary to use "bypassSecurityTrustHtml" for line breaks or lists to work.

Brendan B
  • 369
  • 3
  • 19
2

You can use a pipe like

import { Pipe, Sanitizer } from '@angular/core';

@Pipe({name: 'safe'})
export class SafeHtml {
  constructor(private sanitizer:Sanitizer){}

  transform(html) {
    return this.sanitizer.bypassSecurityTrustHtml(html);
  }
}

and use it like

<span [innerHTML]="myAlertMessage | safe"></span>

where myAlertMessage can contain <br> or <p>

See also In RC.1 some styles can't be added using binding syntax

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

Try to use \n in your myAlertMessage text. Something like that: "\n Some alert text \n Newline of the alert text";

And use a <pre> html tag in your component HTML file like that:

<div>
  <p><pre>{{ myAlertMessage }}</pre></p>
</div>
Worthwelle
  • 1,244
  • 1
  • 16
  • 19
OlegGuy
  • 41
  • 7