ngPreserveWhitespaces doesn't work (Angular 15/17)

49 Views Asked by At

Read about preserving whitespaces in Angular: https://angular.io/api/core/Component#preserving-whitespace

But for some reason I can't preserve them in template using ngPreserveWhitespaces Even when addidng preserveWhitespaces: true doesn't change a thing.

here's stackblitz example

https://stackblitz.com/edit/angular-gaal3c?file=src%2Fmain.ts

Am I doing something wrong?

1

There are 1 best solutions below

0
Naren Murali On

If you inspect element that text and double click it you will see that the white spaces are not actually removed, as to why your not able to visibly see the spaces, is because of CSS.

white-space

normal (default)

Sequences of white space are collapsed. Newline characters in the source are handled the same as other white space. Lines are broken as necessary to fill line boxes.

Ways to stop the collapsing, you can set the white-space property to use any of the below styles where Spaces and tabs is set to preserve (for example: pre)

white space style New lines Spaces and tabs Text wrapping End-of-line spaces End-of-line other space separators
normal Collapse Collapse Wrap Remove Hang
nowrap Collapse Collapse No wrap Remove Hang
pre Preserve Preserve No wrap Preserve No wrap
pre-wrap Preserve Preserve Wrap Hang Hang
pre-line Preserve Collapse Wrap Remove Hang
break-spaces Preserve Preserve Wrap Wrap Wrap

ts

import 'zone.js';
import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule],
  template: `
    <div ngPreserveWhitespaces style="white-space: pre">
    whitespaces   are    preserved                here
    <span>    and here </span>
</div>
    <div ngPreserveWhitespaces style="white-space: break-spaces">
    whitespaces   are    preserved                here
    <span>    and here </span>
</div>
  `,
  preserveWhitespaces: true,
})
export class App {
  name = 'Angular';
}

bootstrapApplication(App);

stackblitz