1

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 class="form-check col-md-6"
                                *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>
4
  • Can you share your entire HTML form as well as all of the pertinent form code in the component class? Commented Apr 27, 2022 at 18:27
  • Hi @PaulThorsen. I added the html form and the component is already there. Commented Apr 27, 2022 at 18:33
  • Is that the entire component class? Where are specilizedArea and companyForm initialized? What does saveCompany() look like? Commented Apr 27, 2022 at 18:36
  • 1
    In addCheckboxesToForm method did you try to initialize it with disabled: true? Like this: new FormControl({value: false, disabled: true}) Commented Apr 27, 2022 at 18:36

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the prompt response. :) It's working now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.