如何在Dialog中以转置MatTable形式展示MatTable行数据?
实现Dialog中转置MatTable的展示方案
1. 转置原表格行数据
先把原MatTable的单条行数据(对象格式)转换成键值对数组,作为转置表格的数据源。比如原数据是:
element = {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'};
转置为:
transposedData = [ {attributeName: 'Position', attributeValue: '1'}, {attributeName: 'Name', attributeValue: 'Hydrogen'}, {attributeName: 'Weight', attributeValue: '1.0079'}, {attributeName: 'Symbol', attributeValue: 'H'} ];
可以用通用转换函数实现:
transposeRowData(row: any): {attributeName: string, attributeValue: string}[] { return Object.entries(row).map(([key, value]) => ({ attributeName: key.charAt(0).toUpperCase() + key.slice(1), attributeValue: String(value) })); }
2. 配置Dialog组件的MatTable
在Dialog组件中定义表格列和数据源:
import {Component, Inject} from '@angular/core'; import {MAT_DIALOG_DATA} from '@angular/material/dialog'; @Component({ selector: 'transposed-table-dialog', templateUrl: './transposed-table-dialog.html', styleUrls: ['./transposed-table-dialog.css'] }) export class TransposedTableDialogComponent { displayedColumns: string[] = ['attributeName', 'attributeValue']; transposedData: {attributeName: string, attributeValue: string}[]; constructor(@Inject(MAT_DIALOG_DATA) public data: any) { this.transposedData = this.transposeRowData(data.row); } private transposeRowData(row: any): {attributeName: string, attributeValue: string}[] { return Object.entries(row).map(([key, value]) => ({ attributeName: key.charAt(0).toUpperCase() + key.slice(1), attributeValue: String(value) })); } }
3. 编写Dialog模板(HTML)
用MatTable实现两列布局,设置表头和单元格内容:
<h2 mat-dialog-title>Element Details</h2> <mat-dialog-content> <table mat-table [dataSource]="transposedData" class="transposed-table"> <!-- Attribute Name Column --> <ng-container matColumnDef="attributeName"> <th mat-header-cell *matHeaderCellDef> AttributeName </th> <td mat-cell *matCellDef="let element"> {{element.attributeName}} </td> </ng-container> <!-- Attribute Value Column --> <ng-container matColumnDef="attributeValue"> <th mat-header-cell *matHeaderCellDef> AttributeValue </th> <td mat-cell *matCellDef="let element"> {{element.attributeValue}} </td> </ng-container> <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr> <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr> </table> </mat-dialog-content> <mat-dialog-actions> <button mat-button mat-dialog-close>Close</button> </mat-dialog-actions>
4. 添加样式实现居中效果
在Dialog的CSS文件中设置表格样式,让内容居中:
.transposed-table { width: 100%; border-collapse: collapse; } .transposed-table th, .transposed-table td { text-align: center; padding: 8px; border: 1px solid #ddd; } .transposed-table th { background-color: #f5f5f5; }
5. 调用Dialog展示转置表格
在原表格组件中,点击行时打开Dialog并传入当前行数据:
openTransposedTableDialog(row: any): void { this.dialog.open(TransposedTableDialogComponent, { width: '400px', data: {row: row} }); }
这样就能实现你需要的两列居中表格样式,取代原示例中的FormFields布局。
内容的提问来源于stack exchange,提问作者Dnyaneshwar
相关产品推荐
相关产品推荐

