首页 > 解决方案 > 角度复选框仅保存已更改的复选框

问题描述

我有一个使用以下方法构建的复选框列表:

        <div *ngFor="let rule of rules">
      <div class="form-check">
        <input type="checkbox" [(ngModel)]="rule.isActive" name="{{rule.ruleId}}" id="{{rule.ruleId}}" class="form-check-input">
        <label class="form-check-label"> {{rule.description}} - {{rule.message}}</label>
      </div>
    </div>

所有这些都在以下表格中:

<form #ruleForm="ngForm" (ngSubmit)="updateRule(ruleForm.value)" novalidate>

在 updateRule 方法中是否有知道哪些复选框已更改?我必须进行保存,但与其全部保存,我只想保存已更改的那些。

标签: angular

解决方案


您可以跟踪检查的规则 id 您可以通过以下方式进行操作:

组件.html

  <div *ngFor="let rule of rules">
     <div class="form-check">
        <input type="checkbox" (change)="onCheck($event,rule.ruleId)" [checked]="rule.isActive"  value="{{rule.ruleId}}" name="{{rule.ruleId}}" id="{{rule.ruleId}}" class="form-check-input">
     <label class="form-check-label"> {{rule.description}} - {{rule.message}}</label>
    </div>
  </div>

组件.ts

activeRulesIds= []; // declare and initialize'

...........
...........
...........

onCheck(event, $value) {
    if (event.target.checked) {
      this.activeRulesIds.push($value);
    }
    else {
      this.activeRulesIds.splice(this.activeRulesIds.indexOf($value), 1);
    }
 }

推荐阅读