Home > database >  Dynamically Disable FormArray in Angular
Dynamically Disable FormArray in Angular

Time:04-28

I have multiple checkboxes as a FormArray. When page load I want to disable all those checkboxes.

I tried in the below mentioned way but it didn't work.

Can someone please explain me on this?

.ts file

public myForm: FormGroup = new FormGroup({
    name: new FormControl('', Validators.required),
    specialized: new FormArray([]),
  });

ngOnInit(): void {
      this.companyForm.controls['specialized'].disable();
}

  get myFormArray() {
    return this.myForm.controls.specialized as FormArray;
  }

  private addCheckboxesToForm() {
    this.specilizedArea.forEach(() => this.myFormArray.push(new FormControl(false)));
  }

.html file

<form [formGroup]="myForm">
    <div 
                                *ngFor="let order of myFormArray.controls; let i = index">
    
                                <label formArrayName="specialized">
                                    <input type="checkbox" [formControlName]="i">
                                    {{specilizedArea[i]?.description}}
                                </label>
    
                            </div>
     <button (click)="saveCompany()"> ADD</button>
    </form>

CodePudding user response:

In ngOnInit you need to call method addCheckboxesToForm and inside that method just create FormControls with disabled: true property, it should look like this:

private addCheckboxesToForm() {
    this.specilizedArea.forEach(() => this.myFormArray.push(new FormControl({value: false, disabled: true})));
  }

Here is quick example that I created with your code: https://stackblitz.com/edit/angular-ivy-bmnfcd?file=src/app/app.component.ts

  • Related