0

I have a form with checkboxes in the form of a list. When I check a checkbox, the value updates in my formgroup but at the HMI level, the checkbox does not remain checked

ngOnInit(){
    const validators = [];
    if(this._isRequired){
      validators.push(Validators.required);
    }
    this.controlFormGroup.addControl(this.controlName, new FormArray([]));
    
    this.addCheckboxes();
    this.onComponentReady.emit(this.controlFormGroup);
  }
  get optionsFormArray() {
    console.log(this.controlFormGroup.controls[this.controlName]);
    return this.controlFormGroup.controls[this.controlName] as FormArray;
  }
  private addCheckboxes() {
    this.options.forEach(() => this.optionsFormArray.push(new FormControl(false)));
  }

<div [formGroup]="controlFormGroup">
    <div [formArrayName]="controlName" *ngFor="let option of optionsFormArray.controls; let i = index" [ngClass]="orientation">
        <mat-checkbox [formControlName]="i">
            {{options[i].label}}
        </mat-checkbox>
    </div>
    <mat-error *ngIf="controlFormGroup.controls[controlName].touched && controlFormGroup.controls[controlName].hasError('required')">
        <span [innerHTML]="errorMessage"></span>
    </mat-error>
</div>

I don't understand the problems

dna
  • 486
  • 1
  • 9
  • 18
  • you can try using the [checked] attribute on the checkbox – Ben Bradshaw Jan 31 '21 at 18:49
  • i thing you can find your answer in https://stackoverflow.com/questions/40927167/angular-reactiveforms-producing-an-array-of-checkbox-values – Khashayar Pakkhesal Jan 31 '21 at 19:27
  • your code works, see a forked stackblitz:https://stackblitz.com/edit/angular-buheff?file=src/app/checkbox-configurable-example.html, you has the error in other place. Note I wrote `
    ` to avoid initials errors
    – Eliseo Jan 31 '21 at 20:01
  • The link does not open @Eliseo – dna Feb 01 '21 at 23:05
  • @dna, try again, I can open it :( – Eliseo Feb 02 '21 at 08:48
  • Thanks it looks to work. There I will change a may the operation but I do not know how to use ControlValueAccessor on a list of checkboxes as I currently have. I want to be inspired by this: https://stackblitz.com/edit/angular-eznzw5?file=src%2Fapp%2Fcontrol-value-accessor-connector.ts – dna Feb 03 '21 at 11:42

0 Answers0