I was surprised what Angular removes spaces between inline HTML tags following each other.
<p><span>1</span> <span>2</span> <span>3</span></p>
This code will be rendered as "123"
instead of "1 2 3"
.
Is this behavior correct?
https://stackblitz.com/edit/angular-remove-spaces
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.
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
)
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With