【问题标题】:Bind comma separated list to checkboxes in Angular 9将逗号分隔列表绑定到Angular 9中的复选框
【发布时间】:2020-12-08 17:33:32
【问题描述】:

在我的反应形式中,我有一个数组,我使用以下语法将复选框列表绑定到: 数组的结构是 {id:number, name:string}

TS

ngOnInit(): void {
 this.initFCForm();
 this.addCheckboxes();
}

initFCForm(): void {
this.fcForm = this.formBuilder.group({
  frequency : new FormControl('', [Validators.required]),
  rules: new FormArray([])
});
}

get rulesFormArray() {
  return this.fcForm.controls.rules as FormArray;
}
private addCheckboxes() {
  this.businessrules.forEach(() => this.rulesFormArray.push(new FormControl(false)));
}

HTML

 <label class="col-md-7" formArrayName="rules" 
         *ngFor="let rule of rulesFormArray.controls; let i = index">
               <input type="checkbox" [formControlName]="i">
                                    {{businessrules[i].name}}
  </label>

现在我需要在页面加载时填充它以选择 firstthird 选项。我尝试了以下代码,但它只选择了前两个选项。

TS

this.fc.rules.patchValue([1,3])

【问题讨论】:

  • 您应该将复选框的formControl 设置为rule 属性,而不是当前索引的formControlName

标签: arrays angular typescript angular-reactive-forms


【解决方案1】:

当你执行 this.fc.rules.patchValue([1,3]) 时,它会将值 1 设置为规则 FormArray 的第一个控件,将值 3 设置为规则 FormArray 的第二个控件,但第三个则不设置。

复选框 formcontrol 需要一个布尔值(true 或 false),在这里,当使用 patch 设置 1 和 3 时,值会自动“转换”为 true,因为它们是真实值。

如果你想填充第一个和第三个值,试试这个:

this.fc.rules.patchValue([true,null, true])

【讨论】:

  • 谢谢@thib_o_o 做到了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-13
  • 1970-01-01
  • 2014-07-04
  • 2012-08-02
  • 1970-01-01
  • 2021-02-18
  • 2013-08-11
相关资源
最近更新 更多