Home > Mobile >  How to check and disable a checkbox, when other 3 checkbox are checked, in Angular
How to check and disable a checkbox, when other 3 checkbox are checked, in Angular

Time:06-22

HTML code (with 4 checkboxes in formArray) :

( I am getting disabled and checked as true, in console, but is unable to reflect it in UI , i.e check and disable the first checkbox on UI, on selection of other three checkboxes)

<div formArrayName="permissionForm">
  <div *ngFor="let subModule of permissionForm.value; let i = index" [formGroupName]="i">
    <input type="text" readonly formControlName="moduleGroupName"  style="margin-top: 5px;" />
    <br />

    <label >
                <input
                  type="text"
                  readonly
                  formControlName="subModules"
                  
                />
     </label>
    <input type="checkbox" formControlName="view" id="view1" />
    <input type="checkbox" formControlName="add" id="add"(change)="isCheckedAdd($event)"/>
    <input type="checkbox" formControlName="edit" (change)="isCheckedEdit($event)" />
    <input type="checkbox" formControlName="delete" (change)="isCheckedDelete($event)"/>
  </div>
</div>

TS Code : (Here add, edit and delete are boolean values) ( I am getting disabled and checked as true, in console, but is unable to reflect it in UI , i.e check and disable the first checkbox on UI, on selection of other three checkboxes)

isCheckedAdd(event) {
  let x = < HTMLInputElement > document.getElementById("view1");
  this.add = true;
  if (this.add == true && this.edit == true && this.delete == true) {
    x.checked = true;
    x.disabled = true;
  }
}

isCheckedEdit(event) {
  let x = < HTMLInputElement > document.getElementById("view1");
  this.edit = true;
  if (this.add == true && this.edit == true && this.delete == true) {
    x.checked = true;
    x.disabled = true;
  }
}

isCheckedDelete(event) {
  let x = < HTMLInputElement > document.getElementById("view1");
  this.delete = true;
  if (this.add == true && this.edit == true && this.delete == true) {
    x.checked = true;
    x.disabled = true;
  }
}

CodePudding user response:

You can use disable() method of FormControl.

The code should be like the following

In HTML,

<input type="checkbox" formControlName="add" id="add"(change)="isCheckedAdd(i)"/>

In TS,

isCheckedAdd(i: number) {
  const permissionFormControls = this.form.controls.permissionForm as FormArray; // Not sure what the name of FormGroup you are using but I assume it's "form"
  permisionFormControls[i].controls.edit.disable();
  permisionFormControls[i].controls.delete.disable();
}
  • Related