【发布时间】:2021-10-15 09:58:27
【问题描述】:
我有一个工作正常的垫表,所有值都以 DB 返回的格式精确显示
<mat-table #table [dataSource]="queryResults" matSort >
<ng-container *ngFor="let column of displayedColumns" matColumnDef="{{column.name}}">
<mat-header-cell *matHeaderCellDef mat-sort-header>{{ column.viewValue }}</mat-header-cell>
<mat-cell *matCellDef="let item">{{item[column.name]}}</mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumnsKeys; sticky: true" ></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumnsKeys;"></mat-row>
</mat-table>
每个项目的数据结构看起来像这样。用户可以从中选择从数据库返回的 300 多列,所以我不想硬编码表定义,而是有一个 JSON 结构来定义列及其值
export interface SearchFields {
name: string;
viewValue: string;
fieldType?: string;
dispFormat?: string;
}
现在我想使用 dispFormat 有条件地格式化一些值。 dispFormat 的可能值为''(留空)currency 或number
我不确定如何实现货币或数字管道,或者没有基于列定义的格式。我尝试添加不正确的 *ngIf
<mat-table #table [dataSource]="queryResults" matSort >
<ng-container *ngFor="let column of displayedColumns" matColumnDef="{{column.name}}">
<mat-header-cell *matHeaderCellDef mat-sort-header>{{ column.viewValue }}</mat-header-cell>
<ng-template #currValue *ngIf="column.dispFormat=='currency'" ><mat-cell *matCellDef="let item" >{{item[column.name] | currency:'USD':true:'2.2-4'}}</mat-cell></ng-template>
<ng-template #noFormatValue *ngIf="column.dispFormat==''" > <mat-cell *matCellDef="let item" >{{item[column.name]}}</mat-cell></ng-template>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumnsKeys; sticky: true" ></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumnsKeys;"></mat-row>
</mat-table>
但是由于混合 *ngIf 和 *matCellDef 会产生错误
ERROR TypeError: Cannot read property 'template' of undefined
如何根据条件格式化值?
编辑 - 根据要求,添加示例数据
示例数据源为:
[{name: 'Company A',
accountspayable: 172286000,
accumulatedamortization: null,
beta: 0.5718,
bookvalue: 15.128,
buy: 0},
{name: 'Company B',
accountspayable: 112676000,
accumulatedamortization: 1689965,
beta: 0.5,
bookvalue: 27.5,
buy: 1},
{name: 'Company C',
accountspayable: 126546000,
accumulatedamortization: 1889965,
beta: 0.168,
bookvalue: 10,
buy: 5}
]
列定义为:
[
{ name: 'name', viewValue: 'Name',dispFormat: '' },
{ name: 'accountspayable', viewValue: 'Accounts Payable', dispFormat: 'currency' },
{ name: 'accumulatedamortization', viewValue: 'Accumulated Amortization', dispFormat: 'currency' },
{ name: 'beta', viewValue: 'Beta', dispFormat: 'number' },
{ name: 'bookvalue', viewValue: 'Book Value', dispFormat: 'currency' },
{ name: 'buy', viewValue: 'Buy', dispFormat: 'number' }
]
【问题讨论】: