Preserve leading whitespace within a <td> of a table using Angular

Viewed 922

I'm using a project with Angular and Metronic (https://preview.keenthemes.com/metronic/demo1/index.html) and I need to put some information in a table, this information is words that start with white spaces and I need that these white spaces are printed, but the table gives a trim in the words.

This is my code:

    <table style="width:100%" class="table table-striped table-hover table-sm" [mfData]="list" #mf="mfDataTable">
   <thead>
    <tr class="bg-primary text-light">
     <th style="width: 10%"><mfDefaultSorter by="code">Code<i class="fa fa-sort"></i></mfDefaultSorter></th>
     <th style="width: 30%"><mfDefaultSorter by="desc">Desc<i class="fa fa-sort"></i></mfDefaultSorter></th>
    </tr>
   </thead>
   <tbody>
    <tr *ngFor="let item of mf.data | filterBy:['code', 'desc']:filterText; let i = index">
     <td>{{ item.code }}</td>
     <td>{{ item.desc }}</td>
    </tr>
   </tbody>
  </table>

And the result was more or less this:

enter image description here

2 Answers

Wrapping your values in <pre> tags will preserve the leading and trailing whitespace.

   <tbody>
    <tr *ngFor="let item of mf.data | filterBy:['code', 'desc']:filterText; let i = index">
     <td><pre>{{ item.code }}</pre></td>
     <td><pre>{{ item.desc }}</pre></td>
    </tr>
   </tbody>

Keep in mind that this will prevent these values from wrapping. If you want to allow the text to wrap and also preserve your whitespaces, you can create a css selector and add whitespace: pre-wrap; to it.

You can change the white-space CSS value

td {
    white-space: pre-wrap;
}
Related