'How do I change the format of a value in a table?
I have a table that displays the following values:
const COLS = [
{ value: "NumCheck", displayName: '#Check' },
{ value: "Date", displayName: 'Date' },
{ value: "Obj", displayName: 'Object' },
{ value: "Sum", displayName: 'Sum' }
];
And I want the Sum value to be displayed in this format #.00.
How can this be done if I have such a table?
<table mat-table class="tb" [dataSource]="dataSource">
<ng-container [matColumnDef]="column.value" *ngFor="let column of allCols;">
<th mat-header-cell *matHeaderCellDef>
{{column.displayName}}
</th>
<td mat-cell *matCellDef="let row">
{{column.value === 'Date' ? (row[column.value] | date : 'dd.MM.yyyy, HH:mm'): row[column.value]}}
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns; sticky: true"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>
Solution 1:[1]
Use the number pipe
{{column.value === 'Date' ? (row[column.value] | date : 'dd.MM.yyyy, HH:mm'): ((column.value === 'Sum') ? (row[column.value] | number:'.2-2'):row[column.value])}}
Solution 2:[2]
Angular switch case attribute can be used, just like the example below, the parameter sent can be formatted according to the type of data.
I use Colums.ts
I use a columns entity of propertytype, this way I can format it according to which parameter type.
<table mat-table [dataSource]="data" matSort (matSortChange)="sortData($event)" class="mat-elevation-z8">
<ng-container [matColumnDef]="column.key" *ngFor="let column of columns">
<th mat-header-cell cdkDrag *matHeaderCellDef mat-sort-header="{{ column.key }}">
{{ column.columnName }}
</th>
<td mat-cell *matCellDef="let col">
<ng-container [ngSwitch]="column.propertyType">
<ng-container *ngSwitchCase="'Date'">
<ng-container *ngTemplateOutlet="dateTemp"></ng-container>
</ng-container>
<ng-container *ngSwitchCase="'Number'">
<ng-container *ngTemplateOutlet="numberTemp"></ng-container>
</ng-container>
<ng-container *ngSwitchCase="'String'">
<ng-container *ngTemplateOutlet="stringTemp"></ng-container>
</ng-container>
<ng-template #dateTemp>
{{col[column.key] | date : 'dd.MM.yyyy'}}
</ng-template>
<ng-template #numberTemp>
{{col[column.key] | number}}
</ng-template>
<ng-template #stringTemp>
{{col[column.key]}}
</ng-template>
<ng-container *ngSwitchDefault>
...
</ng-container>
</ng-container>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
</table>
for example propertytype
- Date
- Number
- String
- Other
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 |
