jack
jack

Reputation: 183

how to disable checkbox when any of other is checked angular 7

<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> 

I need to disable Z checkbox if any of other is checked.And also if Z checkbox is selected I need to disable all other other checkboxes.

How to achieve this?

Upvotes: 0

Views: 3516

Answers (1)

G. Tranter
G. Tranter

Reputation: 17918

You need to respond to the change event for each checkbox and enable or disable the checkbox form controls accordingly:

<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();
  }
}

Upvotes: 1

Related Questions