首页 > 解决方案 > 带有 mat-checkbox 的 Angular 复选框列表

问题描述

我有一个带有列表形式的复选框的表单。当我选中一个复选框时,我的表单组中的值会更新,但在 HMI 级别,复选框不会保持选中状态

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>

我不明白问题

标签: angularcheckboxreactive

解决方案


推荐阅读