You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular12表格行编辑控制与Add按钮多字段校验需求

Angular 12 内联可编辑表格优化方案

一、实现行级编辑权限控制

通过行数据的type字段判断编辑权限,先定义不可编辑的类型集合,再替换原有索引判断逻辑:

  1. 在组件类中声明不可编辑类型常量:
readonly NON_EDITABLE_TYPES = ['Per Chase MRR', 'Per Chase IRR', 'Mileage Reimbursement','Up-Charge'];
  1. 添加判断行是否不可编辑的方法:
isRowNonEditable(type: string): boolean {
  return this.NON_EDITABLE_TYPES.includes(type);
}
  1. 修改HTML模板的编辑状态判断,替换原索引判断(i <=3):
<!-- Type列 -->
<td>
  <ng-container *ngIf="isRowNonEditable(group.value.type)">
    {{ group.value.type }}
  </ng-container>
  <select
    *ngIf="!isRowNonEditable(group.value.type)"
    class="custom-select drop form-control"
    formControlName="type"
    (change)="onChange($event, i)"
  >
    <option disabled="" value="">Choose Charge</option>
    <option
      *ngFor="let charge of dropdownList"
      [value]="charge.name"
      title="charge.name"
    >
      {{ charge.name }}
    </option>
  </select>
</td>

<!-- Description列 -->
<td class="width-textrestarea">
  <ng-container *ngIf="isRowNonEditable(group.value.type)">
    {{ group.value.description }}
  </ng-container>
  <input
    type="text"
    class="form-control"
    formControlName="description"
    placeholder="description"
    *ngIf="!isRowNonEditable(group.value.type)"
    (focusout)="addTotal(i)"
  />
</td>

<!-- Quantity列 -->
<td class="w-60">
  <ng-container *ngIf="isRowNonEditable(group.value.type)">
    {{ group.value.quantity }}
  </ng-container>
  <input
    type="text"
    class="form-control"
    formControlName="quantity"
    placeholder="quantity"
    *ngIf="!isRowNonEditable(group.value.type)"
    (focusout)="addTotal(i)"
  />
</td>

Unit Cost和Total列保持原有只读逻辑即可,无需调整。

二、完善Add按钮启用条件

修改disableAdd()方法,同时校验每行的type、description、quantity字段:

disableAdd() {
  // 只要有一行必填字段未填,就禁用Add按钮
  return this.getFormData.controls.some(control => {
    const { type, description, quantity } = control.value;
    return !type || !description || !quantity;
  });
}

利用Array.some()简化逻辑:遍历所有行,存在任意一行必填字段为空时返回true(禁用按钮),全部满足条件则返回false(启用按钮)。

内容的提问来源于stack exchange,提问作者Bhrungarajni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 15:55:20