Why Angular removes spaces between inline tags?

As mentioned in the Angular documentation, the compiler option preserveWhitespaces is false by default. With that setting, the Angular compiler removes the spaces between your span elements. To preserve the spaces without changing the compiler option, you can use the Angular entity &ngsp; which is replaced by a space in the rendered HTML:

<p><span>1</span>&ngsp;<span>2</span>&ngsp;<span>3</span></p>

An alternative method is to set the ngPreserveWhitespaces attribute:

<p ngPreserveWhitespaces><span>1</span> <span>2</span> <span>3</span></p>

See this stackblitz for a demo.


By Angular 6 for better performance Angular team turned off preserveWhitespaces as false.
So If you need to turn that on you need to do it manually, you can do it globally or per component.

True to preserve or false to remove potentially superfluous whitespace characters from the compiled template. Whitespace characters are those matching the \s character class in JavaScript regular expressions. Default is false, unless overridden in compiler options.

See next 2 links for extra details:
https://angular.io/api/core/Component#preservewhitespaces

How to globally set the preserveWhitespaces option in Angular to false?


I don't know why anyone would suggest fixing this via CSS. Angular is too aggressive with its whitespace removal and needs better context awareness.

Using <strong> in the middle of a <p> block works exactly as expected with no whitespace removal. However, if it happens to be next to another inline tag within the same paragraph, such as a <span> or <em>, then the space between the two will be removed, even if there is unwrapped text on either side of the inline elements.

To enable whitespace preservation for the project, assuming you're using the CLI, you'll need to update two files in your project (check the src directory).

tsconfig.app.json

Add this to the end of the document, before the last curly brace:

  "angularCompilerOptions": {
    "preserveWhitespaces": true
  }

main.ts

Change:

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.error(err));

To:

platformBrowserDynamic().bootstrapModule(AppModule, {
  preserveWhitespaces: true
}).catch(err => console.error(err));

The first file will preserve whitespace during development (ng serve) and the second will do the same for productions builds (ng build --prod)

Tags:

Spaces

Angular