首页 > 解决方案 > 如何在角度材料中动态启用更新按钮

问题描述

在此处输入图像描述

我有一个垫表,其中有两列,一列是用户角色,第二列有一个更新按钮,现在我想要的是每当用户在用户角色下拉列表中选择任何选项时,更新按钮都应该启用。但是,如果列表中的选定项目是相同的,更新按钮应该像以前一样保持禁用状态。

任何机构可以帮助我吗?

这是我的专栏详细信息:

<!-- User Role Column-->
<ng-container matColumnDef="roleName">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> User Role </th>
    <td mat-cell *matCellDef="let element" data-title="User Role:">
        <mat-select [(ngModel)]="element.clientRoleId" class="table-select">
             <mat-option [value]="clientRole.clientRoleId" *ngFor="let clientRole of clientRoleList" >
              {{ clientRole.roleName }}
            </mat-option>
          </mat-select> 
    </td>
</ng-container>

<!-- Update User Role Column -->
<ng-container matColumnDef="updateUserRole">
    <th mat-header-cell *matHeaderCellDef>Update User Role</th>
    <td mat-cell *matCellDef="let element" data-title="Update User Role:"> 
        <button mat-stroked-button color="blue-strok" [disabled]="element.roleName">Update</button>
    </td>
</ng-container>

所有数据都来自一个 api。

标签: angular

解决方案


您需要做的就是存储clientRoleId用户的姓名首字母。

所以要做到这一点,我将创建一个“临时”变量来仅存储clientRoleId带有map.

// this array is just to simulate your data
users = [
  { clientRoleId: 1, name: "User1" },
  { clientRoleId: 2, name: "User2" },
  { clientRoleId: 1, name: "User3" }
];

tempUsers = []

ngOnInit(){
  this.tempUsers = this.users.map(obj => obj.clientRoleId)
}

然后在您的模板上,mat-select由于您的[(ngModel)]="element.clientRoleId". 所以唯一要做的就是检查新值是否与旧值相同。

<button mat-stroked-button 
        color="blue-strok" 
        [disabled]="element.clientRoleId == tempUsers[i]"> // <- Here thanks to the 'temp' array
  Update
</button>

是一个 stackblitz 示例,向您展示一个可行的建议。

PS:如果我可以为您可能的下一个问题提出建议,那么为您的问题提供一个 stackblitz 最小表示总是更好地帮助用户。


推荐阅读