22

UPDATE: Both ways from Chris and Mark work.

I am using Angular 2. I try to show two continuous spaces between a and bin the page. I've tried all of these, but none of them works:

{{text}}

text = "a\00a0\00a0b";
text = `a\00a0\00a0b`;
text = "a  b";
text = `a  b`;
text = "a  b";
text = `a  b`;

How can I make it work?

Hongbo Miao
  • 38,184
  • 54
  • 150
  • 228

3 Answers3

25

Bind to DOM property innerHTML instead of DOM property textContent (which is what {{}} binds to):

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

text = "a&nbsp;&nbsp;b";
Mark Rajcok
  • 356,856
  • 113
  • 487
  • 490
  • 1
    In version 6.0.0 I found that you have to add single quotes around the text string since it otherwise assumes the whole thing is a variable. You also can't take the square brackets from around innerHTML as that complains for a different reason. So basically ```text = "'a  b'"``` is what worked for me. – crowmagnumb May 17 '18 at 18:13
21

I believe you're getting this because of the nature of html stripping spaces.

You could perhaps use the white-space: pre css property on whatever element you are rendering that text.

function MyCtrl($scope) {
  $scope.text = 'a      b';
}
...
<p style="white-space: pre">{{text}}</p>

I don't know alot about your application, but perhaps this will suffice.

Demo

Chris
  • 53,920
  • 18
  • 108
  • 124
12

use '&#160;' instead of '&nbsp;' in template.

nehem
  • 10,894
  • 6
  • 51
  • 76
Rahul K
  • 888
  • 5
  • 16