'Material table cells with specific width according to predefined length
I will show my code first.
<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef> No. </th>
<td mat-cell *matCellDef="let element"> {{element.position}} </td>
</ng-container>
Everything works fine, my requirement is to display text but just a fixed length of it. For example, if I have a text that is 50
characters long, the requirement is to display 40
. I have many cells in each row, many cells of fixed length.
To clarify, here my difficulty is how to set width with some text length, I saw many examples but the column width was set in the CSS file. How can I achieve that? Thanks in advance.
Solution 1:[1]
One simple way to achieve this is to set the width of the td
via Angular's built in [ngStyle]
with some calculation of the element's length.
<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let element"
[ngStyle]="{'max-width': ((element.name.length) - 20) + 'ch', 'overflow': 'hidden' }">
{{element.name}}</td>
</ng-container>
Here the max-width
(in ch
, see MDN) of the element is defined by element.name.length
minus 20
(specify as you like). Also overflow: hidden
is set, so the rest of the text won't be shown inside the table cell.
See below for the differences between a fixed table and normal table.
Fixed table
Normal table
Here's a StackBlitz to illustrate above.
Solution 2:[2]
Try this,
You can set maxCharLength as per your requirements. Also mat-table doesn't need <th>
or <td>
tags.
<ng-container matColumnDef="position">
<mat-header-cell *matHeaderCellDef> Name </mat-header-cell>
<mat-cell *matCellDef="let element" [innerHTML]="element.position" [maxCharLength]="40">
</mat-cell>
</ng-container>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Niromy |