如何在选中其他任何一个时禁用复选框7

时间:2019-03-13 18:25:47

标签: angular-material angular7

<div>
  <mat-checkbox formControlName="A">A</mat-checkbox>
  <mat-checkbox formControlName="B">B</mat-checkbox>
  <mat-checkbox formControlName="C">C</mat-checkbox>
  <mat-checkbox formControlName="D">D</mat-checkbox>
  <mat-checkbox formControlName="E">E</mat-checkbox>
  <mat-checkbox formControlName="F">F</mat-checkbox>
  <mat-checkbox formControlName="Z">Z</mat-checkbox>   
</div> 

如果选中了其他复选框,则需要禁用Z复选框。此外,如果选中了Z复选框,则需要禁用所有其他复选框。

如何实现?

1 个答案:

答案 0 :(得分:1)

您需要响应每个复选框的更改事件,并相应地启用或禁用复选框表单控件:

<mat-checkbox formControlName="A" (change)="checkboxAFChanged($event.checked)">A</mat-checkbox>
<mat-checkbox formControlName="B" (change)="checkboxAFChanged($event.checked)">B</mat-checkbox>
<mat-checkbox formControlName="C" (change)="checkboxAFChanged($event.checked)">C</mat-checkbox>
<mat-checkbox formControlName="D" (change)="checkboxAFChanged($event.checked)">D</mat-checkbox>
<mat-checkbox formControlName="E" (change)="checkboxAFChanged($event.checked)">E</mat-checkbox>
<mat-checkbox formControlName="F" (change)="checkboxAFChanged($event.checked)">F</mat-checkbox>
<mat-checkbox formControlName="Z" (change)="checkboxZChanged($event.checked)">Z</mat-checkbox>   

TS:

checkboxAFChanged(checked) {
  if (checked) {
    this.formGroup.controls.Z.disable();
  } else if (!(this.formGroup.controls.A.value 
      || this.formGroup.controls.B.value 
      || this.formGroup.controls.C.value 
      || this.formGroup.controls.D.value 
      || this.formGroup.controls.E.value 
      || this.formGroup.controls.F.value)) {
    this.formGroup.controls.Z.enable();
  }
}

checkboxZChanged(checked) {
  this.enableControl(this.formGroup.controls.A, !checked);
  this.enableControl(this.formGroup.controls.B, !checked);
  this.enableControl(this.formGroup.controls.C, !checked);
  this.enableControl(this.formGroup.controls.D, !checked);
  this.enableControl(this.formGroup.controls.E, !checked);
  this.enableControl(this.formGroup.controls.F, !checked);
}

enableControl(control: AbstractControl, enabled: boolean) {
  if (enabled) {
    control.enable();
  } else {
    control.disable();
  }
}