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

Adding optional change event on html element and js function

我有一个 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)"