12

I have a simple question (I hope this). I have a service that return a string as result. The format is something like this:

" Test1: the association has been accepted.\nTest2: the association has been accepted.\n" "

On the client side (I'm using Angular 1.5.x) I put that string into a object (say the variable $scope.alert.message). After that I want to print that string in a modal. My html is:

<script type="text/ng-template" id="infoTemplate.html">
    <div class="modal-header left" ng-class="['div-' + alert.type, closeable ? 'alert-dismissible' : null]">
        <h3 class="modal-title" id="modal-title">Info</h3>
    </div>
    <div class="modal-body" id="modal-body">
        <img class="imm-info" ng-class="['imm-' + alert.type, closeable ? 'alert-dismissible' : null]" />
        <p class="col-sm-10 col-sm-offset-2">{{alert.message}}</p><button class="col-sm-3 col-sm-offset-5 btn " ng-class="['button-' + alert.type, closeable ? 'alert-dismissible' : null]" ng-click="cancel()">OK</button>
    </div>
</script>

You can see the '{{alert.message}}'. My problem is that my message "doesn't display" the character '\n'. So it doesn't create more than one line. An example here:

example

Massimo
  • 205
  • 1
  • 3
  • 10

4 Answers4

17

I use the white-space: pre-wrap CSS style, e.g. :

<p style="white-space: pre-wrap">{{alert.message}}</p>
Julien Kronegg
  • 4,968
  • 1
  • 47
  • 60
15

Try this in HTML:

<pre>{{ alert.message }}</pre>

Already answered here:

The < pre > wrapper will print text with \n as text

Alex Florin
  • 431
  • 5
  • 14
  • 2
    This also has the side effect that you cannot have html tags in your alert message / they would be rendered as is. Just something to watch out for. EDIT: Today I learned: that actually works as well. – phil Jun 07 '17 at 10:35
  • I didn't know you can also use html inside it. :) I've only ever used it for simple strings. This is good info. – Alex Florin Jun 07 '17 at 10:41
  • Thanks. That's useful info. – Massimo Jun 07 '17 at 11:56
4

\n is not interpreted in html. You need to replace these instances with <br/> elements. You could for example replace them with a regex if you do not want to change the original string.

phil
  • 420
  • 4
  • 14
2

You can write a function where you take the alert-message and split it by "\n" than iterate trough it via *ngFor.

For example:

<p *ngFor="let msg of getMessageSplitted(alert.message)">{{msg}}</p>
Markus G.
  • 1,620
  • 2
  • 25
  • 49
  • 2
    As a sidenote: You should avoid using functions in `*ngFor` as much as possible. Angular does many checks every time the model changes. Since it doesn't know if the change in the model affects the output of your function, it will be called countless times and it will greatly affect the performance if the function does heavy operations. – Alex Florin Oct 31 '17 at 10:53