Angular 16实现点击编辑按钮时禁用其余表格行
解决Angular表格禁止同时编辑多行的问题
方案一:通过状态管理+CSS禁用其他行
这个方案匹配你原本的思路,通过跟踪当前编辑行,给其余行添加禁用样式:
- 组件类中添加状态变量
在组件的.ts文件里新增变量记录当前正在编辑的行:
currentEditingRow: any = null; tempName: string = ''; tempAddress: string = ''; tempCity: string = '';
- 修改
editRow方法逻辑
更新点击事件,确保每次仅一行处于编辑状态:
editRow(row: any) { // 点击当前编辑行则取消编辑 if (this.currentEditingRow === row) { row.editCell = false; this.currentEditingRow = null; // 回滚临时保存的值(可选,按需调整) row.name = this.tempName; row.address = this.tempAddress; row.city = this.tempCity; return; } // 关闭之前正在编辑的行 if (this.currentEditingRow) { this.currentEditingRow.editCell = false; } // 开启当前行编辑状态 row.editCell = true; this.currentEditingRow = row; // 保存当前值用于后续回滚 this.tempName = row.name; this.tempAddress = row.address; this.tempCity = row.city; }
- 更新模板中的行样式判断
修改<tr>的ngClass绑定,仅当存在编辑行且当前行不是编辑行时,添加禁用样式:
<tbody> <tr *ngFor="let cus of customers; let i = index" [ngClass]="{'disableRow': currentEditingRow && currentEditingRow !== cus}" [attr.id]="'row'+i"> <td> <span *ngIf="!cus.editCell">{{cus.name}}</span> <input type="text" class="form-control small cellStyle" [(ngModel)]="cus.name" *ngIf="cus.editCell" /> </td> <td> <span *ngIf="!cus.editCell">{{cus.address}}</span> <input type="text" class="form-control small cellStyle" [(ngModel)]="cus.address" *ngIf="cus.editCell" /> </td> <td> <span *ngIf="!cus.editCell">{{cus.city}}</span> <input type="text" class="form-control small cellStyle" [(ngModel)]="cus.city" *ngIf="cus.editCell" /> </td> <td> <div class="btn-toolbar"> <button class="btn btn-primary small" title="Edit" (click)="editRow(cus)" *ngIf="!cus.editCell"> <fa-icon icon="pen-to-square"></fa-icon> </button> </div> </td> </tr> </tbody>
保留你的CSS样式:
.disableRow{ opacity:0.5; pointer-events:none;}
方案二:直接控制编辑按钮显示(更简洁)
从根源阻止用户点击其他编辑按钮,无需依赖CSS:
添加
currentEditingRow状态变量(同方案一)修改
editRow方法(同方案一)更新模板中编辑按钮的显示条件
仅当前无编辑行,或点击的是正在编辑的行时,才显示编辑按钮:
<button class="btn btn-primary small" title="Edit" (click)="editRow(cus)" *ngIf="!cus.editCell && (!currentEditingRow || currentEditingRow === cus)"> <fa-icon icon="pen-to-square"></fa-icon> </button>
这种方式下,编辑某一行时其他行的编辑按钮自动隐藏,完全避免同时编辑的可能,体验更直接。
内容的提问来源于stack exchange,提问作者Moe-Doe
相关产品推荐
相关产品推荐

