Angular 加载时勾选复选框

Angular Check checkboxes on load

需要你的帮助

我有一组复选框值

colors = ['Black', 'Red', 'White', 'Blue', 'Yellow', 'Grey'];

在 HTML

中实现了它们
<div *ngFor="let color of colors; let i = index" class="checkbox">
        <label>
          <input type="checkbox" class="colors" [value]="color" (change)="addCheckboxData($event)" />
          {{ color }}
        </label>
      </div>

所以它看起来像这样:

我有一组值,当我加载页面时应该检查这些值

  checkedValues = ['Black', 'White', 'Grey'];

我将它们添加到 formarray

color: this._formBuilder.array(this.checkedValues),

它有效并且颜色格式数组具有类似于 checkedValues 数组中的值:

但复选框未选中,因此我希望此值显示为已选中。我怎样才能做到这一点?谢谢

你需要传递一个布尔数组

color: this._formBuilder.array(
              this.colors.map(x=>this.checkedValues.indexOf(x)>=0)),

并像这样管理表格

<form [formGroup]="form">
    <input formControlName="name">
    <div formArrayName="color">
        <div *ngFor="let control of colorFormArray.controls;let i=index">
            <input type="checkbox" [formControlName]="i">{{colors[i]}}
      </div>
        </div>
</form>
<pre>
{{form?.value|json}}
</pre>

好吧,您会看到“颜色”作为布尔值数组的值,例如[true,false,true,false,false,true]

并且您希望该颜色获得一个包含颜色的数组,所以想法是使用 formControl 而不是 formArray 并使用 [ngModel] 和 (ngModelChange)。当我们在 FormGroup 中使用 [ngModel] 时,我们需要使用 [ngModel]="{standalone:true}"

查看表格和.html

this.form2=this._formBuilder.group({
  name:[],
  color:[this.checkedValues] //<--see that is a simple FormControl
})

<form [formGroup]="form2">
        <div *ngFor="let col of colors;let i=index">
            <input type="checkbox" 
           [ngModel]="form2.get('color').value && form2.get('color').value.indexOf(col)>=0" 
           (ngModelChange)="colorChange($event,i)"
           [ngModelOptions]="{standalone:true}"
                 
      >{{colors[i]}}
        </div>
</form>

根据 form2.get('color').value.indexOf

[ngModel] 是对还是错

函数 colorChange 接收到复选框的值和一个索引

  colorChange(checked:boolean,index:number)
  {
    const checkedColors=this.form2.get('color').value || [] //the actual value of the formControl
                                                            //if is null an empty array
    const color=this.colors[index];  //the color selected

    ///if is checked and is not in the array
    if (checked && checkedColors.indexOf(color)<0)
    {
      //concatenate to the value the new color
      //and sort the result array 

      const orderColors=[...checkedColors,color]
                  .sort((a,b)=>this.colors.indexOf(a)-this.colors.indexOf(b))

      //make a setValue
      this.form2.get('color').setValue(orderColors)
    }

    //if not checked

    if (!checked)
      this.form2.get('color').setValue(checkedColors.filter(x=>x!=color))

  }

stackblitz你有两个方法

注意:在这个第二个方法中,我们可以使如果没有颜色select,控件的值变为空。这允许我们使用 Validators.required,例如唯一的就是改变函数 colorChange

  colorChange(checked:boolean,index:number)
  {
        ...

    if (!checked)
    {
      const result=checkedColors.filter(x=>x!=color)
      this.form2.get('color').setValue(result.length>0?result:null)
    }

  }