Home > Enterprise >  Preserve the whitespaces of an element while using *ngFor
Preserve the whitespaces of an element while using *ngFor

Time:08-31

I am using Angular.js, *ngFor for looping over the array and display the values. I want to preserve the spaces of an elements like array is,

 string arr1 = ["    Welcome Angular   ", "Line1", "Line2", "   
 Done   "]

I have used :


<div *ngFor="let arrValue of arr1">
   {{arrValue}}
</div>

current output:

Welcome Angular   
Line1
Line2
Done   

Expected output:

    Welcome Angular   
Line1
Line2
    Done   

How to preserve the spaces of an elements like array without any modification.

Here, link for stackblitz where displaying by looping over. You can perform practical and Please let me know if you figure out way to preserve element with white spaces.

Thank you in advance.

https://stackblitz.com/edit/ngfor-examples?file=app/app.component.ts,app/app.component.css

CodePudding user response:

Use the css style white-space: pre;

css

.preserve-whitespace {
  white-space: pre;
}

ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  arr1 = ['    Welcome Angular   ', 'Line1', 'Line2', '   Done   '];
  name = 'Angular';
}

html

<div *ngFor="let arrValue of arr1" >
  {{ arrValue }}
</div>

forked stackblitz

CodePudding user response:

You could try this

<div *ngFor="let arrValue of arr1">
   <pre>{{arrValue}}</pre>
</div>

CodePudding user response:

Try the following:

<div *ngFor="let arrValue of arr1">
   <pre>
   {{arrValue}}
   </pre>
</div>

CodePudding user response:

Similar to all the answers above you can use CSS's white-space: pre-wrap; to accomplish this goal. You can either do it inline which would look like this:

yourComponent.html

<div style="white-space: pre-wrap;">

Or you could add a CSS attribute to the div you want like so:

styles.scss

.white-space {
  white-space: pre-wrap;
}

yourComponent.html

<div >
  • Related