【问题标题】:How to add buttons edit / delete to mat-table如何将按钮编辑/删除添加到 mat-table
【发布时间】:2019-07-16 10:46:41
【问题描述】:
我想在“动作”列中有两个垫子按钮
一编辑一删除。
这是我的桌子
<table mat-table
[dataSource]="dataSource" multiTemplateDataRows
class="mat-elevation-z8">
<ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay">
<th mat-header-cell *matHeaderCellDef> {{column}} </th>
<td mat-cell *matCellDef="let aliasesData"> {{aliasesData[column]}} </td>
</ng-container>
有columnsToDisplay
columnsToDisplay = ['id', 'domain_id', 'source', 'action'];
我想在每一行的Action栏下都有一个按钮来编辑和删除。
【问题讨论】:
标签:
angular
angular-material
【解决方案1】:
<table mat-table [dataSource]="tableData" class="mat-elevation-z8">
<ng-container *ngFor="let col of tab.table_columns" [matColumnDef]="col.name">
<ng-container *ngIf="col.name !== 'action' ">
<th mat-header-cell *matHeaderCellDef> {{ col.title }} </th>
<td mat-cell *matCellDef="let element"> {{ element[col.name] }}</td>
</ng-container>
<ng-container *ngIf="col.name === 'action' ">
<th mat-header-cell *matHeaderCellDef> {{ col.title }} </th>
<td mat-cell *matCellDef="let element"><button>View Details</button></td>
</ng-container>
</ng-container>
<tr mat-header-row *matHeaderRowDef="displayedColumn"></tr>
<tr mat-row *matRowDef="let row; columns: displayedColumn"></tr>
</table>
【解决方案2】:
我有一个解决方案,但并不完美。
<table mat-table [dataSource]="dataSource"
multiTemplateDataRows class="mat-elevation-z8">
<ng-container matColumnDef="{{column}}"
*ngFor="let column of columnsToDisplay">
<th mat-header-cell *matHeaderCellDef>
{{column !== 'action' ? column : ''}}
</th>
<ng-container *ngIf="column !== 'action'">
<td mat-cell *matCellDef="let aliasesData">
<span>{{aliasesData[column]}}</span>
</td>
</ng-container>
<ng-container *ngIf="column === 'action'">
<td mat-cell *matCellDef="let aliasesData">
<span>
<button>Edit</button>
<button>Delete</button>
</span>
</td>
</ng-container>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
<tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
</table>
您可以使用 ngIf 绑定来检查列 action 并仅显示该列的按钮。
或者有 2 列显示数组
columnsToDisplay = ['id', 'domain_id', 'source'];
columnsForConfig = ['id', 'domain_id', 'source', 'action'];
一个用于渲染,另一个用于底部的配置,并在 ngFor 绑定之后将操作作为单独的部分。
<table mat-table [dataSource]="dataSource" multiTemplateDataRows class="mat-elevation-z8">
<ng-container matColumnDef="{{column}}" *ngFor="let column of columnsToDisplay">
<th mat-header-cell *matHeaderCellDef>
{{column}}
</th>
<td mat-cell *matCellDef="let aliasesData">
<span>{{aliasesData[column]}}</span>
</td>
</ng-container>
<ng-container matColumnDef="action">
<th mat-header-cell *matHeaderCellDef>
actions
</th>
<td mat-cell *matCellDef="let aliasesData">
<button>Edit</button>
<button>Delete</button>
</td>
</ng-container>
<tr mat-header-row *matHeaderRowDef="columnsForConfig"></tr>
<tr mat-row *matRowDef="let row; columns: columnsForConfig;"></tr>
</table>