angular - mat-table creating columns dynamically vs static change table look
问题描述
Sorry if this question is trivial, I'm very new to Angular and Web UI Kingdom
I'm currently looking at this sample project: https://github.com/marinantonio/angular-mat-table-crud
I was replacing the way the columns were created (from static to dynamic) and the table layout changed into something that is hard to read. I am having trouble understanding how/why this is happening. What makes the difference in how I created my columns? But, most importantly, how do i fix it?
Here is what I have:
componnent.html:
<ng-container *ngFor="let column of columns" matColumnDef="{{column.name}}">
<th mat-header-cell *matHeaderCellDef mat-sort-header>{{column.label}}</th>
<td mat-cell *matCellDef="let row"> {{row[column.name]}} </td>
</ng-container>
component.ts
columns: Array<any> = [
{ name: 'id', label: 'ID', cell: (element: any) => `${element.id}` },
{ name: 'title', label: 'Title', cell: (element: any) => `${element.title}` },
{ name: 'state', label: 'State', cell: (element: any) => `${element.state}` },
{ name: 'url', label: 'Url', cell: (element: any) => `${element.url}`},
{ name: 'created_at', label: 'Created at', cell: (element: any) => `${element.created_at}`},
{ name: 'updated_at', label: 'Updated at', cell: (element: any) => `${element.updated_at}`},
]
// displayedColumns = ['id', 'title', 'state', 'url', 'created_at', 'updated_at', 'actions'];
displayedColumns = this.columns.map(x => x.name).concat(['actions']);
I didn't touch the components.css
解决方案
我找到了解决方案!!!
使用 cdkColumnDef 和 cdkHeaderCellDef 而不是 matColumnDef 和 mat-header-cell
<ng-container *ngFor="let column of columns; let colIndex = index" [cdkColumnDef]="column.name">
<mat-header-cell *cdkHeaderCellDef>{{ column.label }}</mat-header-cell>
<mat-cell *cdkCellDef="let row">{{ row[column.name] }}</mat-cell>
</ng-container>
推荐阅读
- c# - 空响应返回 204
- scala - 避免使用 OptionT 的样板(自然变换?)
- python - 使用 pipenv install -r requirements.txt 找到“.dist-info 目录”
- delphi - ServerSocket 只接收一次
- angular-cli - 将 Angular 6 cli 构建使用 Angular/cli@1.7.4 创建的 Angular 应用程序
- git - 使用 git API 和 cURL 的 Git 分支限制
- ios - Firebase 实时数据库查询因用户身份验证后的安全规则而失败,否则工作
- python - pygame.time.wait() 使程序崩溃
- android - 日期/持续时间的 Droid API 22+ 选项(在 Kotlin 中)?
- python - 无法使用 pandas 和 xlsxwriter 将格式添加到 Excel 工作表