在 html 元素和 js 函数上添加可选的更改事件

问题描述

我有一个用于多种类型的 Angular 弹出组件。

对于类型 A 和 B,我在页脚中有一个“操作”部分,用于获取结果并关闭弹出窗口。对于类型 C,我想在选中复选框时关闭弹出窗口(因此,这里我需要使用 change 事件,但这对类型 A 和 B 没有用)。

html:

<ng-container matColumnDef="max">
   <th *matHeaderCellDef mat-header-cell>Max</th>
   <td *matCellDef="let row" [ngClass]="row.actions.maxdisabled ? 'disabled' : ''"
         mat-cell>
      <mat-checkBox (change)="onActionSelected(row)"
                    [(ngModel)]="row.actions.max"
                    [disabled]="row.actions.maxdisabled"></mat-checkBox>
   </td>
</ng-container>

ts:

onActionSelected(row: any): void {
   if (this.source !== 'C') {
      return;
   }

   const data = this.dataSource.data;
   const value = Helpers.getValue(data);

   this.dialogRef.close(value);
}

我仅针对案例 (change)="onActionSelected(row)" 在模板上添加C 事件,如果源类型不是它,则需要检查该方法

我想知道是否存在更优雅的解决方案,可以将更改事件动态添加到复选框并从方法删除验证。

解决方法

您可以向更改事件添加条件,假设行对象包含源属性:

(change)="row.source !== 'C' && onActionSelected(row)"