Angular Material Table 如何通过点击行内mat-select控制同行按钮显隐
实现方案
你不需要手动获取DOM中的按钮组件,直接通过行数据挂载临时状态字段控制显示隐藏即可,这是Angular框架下最符合数据流逻辑的实现方式:
- 修改模板绑定逻辑
首先修改mat-select的点击事件,将当前行数据作为参数传入,同时给操作按钮增加显示状态判断:
<mat-table #table [dataSource]="transactions"> <!-- Category Column --> <ng-container matColumnDef="category"> <mat-header-cell *matHeaderCellDef> Category </mat-header-cell> <mat-cell *matCellDef="let transaction"> <mat-form-field floatLabel="never"> <mat-select [(value)]="transaction.category" placeholder="Category" (click)="onSelectClick(transaction)"> <mat-option *ngFor="let classItem of classes" [value]="classItem.id"> {{classItem.class}} </mat-option> </mat-select> </mat-form-field> </mat-cell> </ng-container> <!-- Action Column --> <ng-container matColumnDef="action"> <mat-header-cell *matHeaderCellDef> Action </mat-header-cell> <mat-cell *matCellDef="let element"> <button *ngIf="element.showActionBtn" mat-flat-button color="accent">Accent</button> </mat-cell> </ng-container> <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row> <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row> </mat-table>
- 补充TS逻辑
在组件的TS文件中处理点击事件,给当前行添加控制按钮显示的状态字段:
// 点击select触发的方法 onSelectClick(currentRow: any): void { // 可选:如果需要只显示当前点击行的按钮,先把所有行的按钮状态重置为隐藏 this.transactions.forEach(item => item.showActionBtn = false); // 把当前点击行的按钮设为显示 currentRow.showActionBtn = true; } // 如果需要在初始化时就给所有数据加默认隐藏的状态,可以在拿到transactions数据后遍历赋值 // 示例:拿到接口返回的transactions后 this.transactions = res.data.map(item => ({...item, showActionBtn: false}));
如果确实需要获取按钮的DOM实例做其他操作,可以给按钮加模板引用变量,通过@ViewChildren查询所有按钮实例,再根据行索引匹配对应按钮即可,不过控制显示隐藏的需求用上述数据驱动的方式更简洁,不需要操作DOM。
内容的提问来源于stack exchange,提问作者Musaffar Patel
相关产品推荐
相关产品推荐

