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
  • 45,290
  • 60
  • 174
  • 267

3 Answers3

27

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
  • 362,217
  • 114
  • 495
  • 492
  • 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
25

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
  • 57,622
  • 19
  • 111
  • 137
12

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

nehem
  • 12,775
  • 6
  • 58
  • 84
Rahul K
  • 888
  • 5
  • 16