【发布时间】: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>
现在我需要在页面加载时填充它以选择 first 和 third 选项。我尝试了以下代码,但它只选择了前两个选项。
TS
this.fc.rules.patchValue([1,3])
【问题讨论】:
-
您应该将复选框的
formControl设置为rule属性,而不是当前索引的formControlName。
标签: arrays angular typescript angular-reactive-forms