angular 中的复选框未给出正确的值

checkbox is not giving correct value in angular

我在表单数组中有一个复选框。我在复选框选择中应用了限制,即选中的复选框不超过 2 个。

         <input type="checkbox"  formControlName="Viewable" class="form-control checkbox"
                        (change)="selectViewable($event)" />

选中第 3 个复选框时,它在事件和 event.target.checked 中给出了不同的值。任何建议我错过了什么。??为什么它给出不同的值

   selectViewable(event){
     console.log(event)
      console.log(event.target.checked)

    if (event.target.checked === true){
      if(this.counter < 2){
        this.counter++
      } else{
         event.target.checked = false;
         this.toastrService.info("You cannot select viewable more than 2");
      }
    } else if(this.counter>0){
      
      this.counter--;
    }
    else{
      event.target.checked = false;
    }
  }


here is my stackblitz
https://stackblitz.com/edit/angular-mbfpfg?file=src%2Fapp%2Fapp.component.ts

您可以手动重置表单的值以确保匹配。在你的 html

<form [formGroup]='myForm'>
  <ng-container formArrayName='myFormArray'>
    <ng-container *ngFor="let item of myFormArray.controls; let i = index" [formGroupName]='i'>
      <input type="checkbox" formControlName="Viewable" class="form-control checkbox" (change)="selectViewable(i, $event)" />
    </ng-container>
  </ng-container>

</form>

在你的 TS

  selectViewable(i, event) {
    console.log(event);
    console.log(event.target.checked);

    if (event.target.checked === true) {
      if (this.counter < 2) {
        this.counter++;
      } else {
        event.target.checked = false;
        this.toastrService.info('You cannot select viewable more than 2');

        this.myFormArray
          .at(i)
          .get('Viewable')
          .setValue(false);
      }
    } else if (this.counter > 0) {
      this.counter--;
    } else {
      event.target.checked = false;
    }
  }

Sample Demo

注意:您不需要跟踪已检查项目的数量,因为表单数组包含所有这些信息。下面也可以工作

  selectViewable(i) {
    const count = this.myFormArray.value.filter(({ Viewable }) => Viewable)
      .length;
    if (count > 2) {
      const control = this.myFormArray.at(i).get('Viewable');
      this.toastrService.info('You cannot select viewable more than 2');
      control.setValue(false);
    }
  }

并且在你的html中不需要通过事件

(change)="selectViewable(i)"

See Demo