在反应式窗体的formGroup中以编程方式选中多个复选框,可以通过以下步骤实现:
formGroup
指令将表单与组件中的FormGroup对象进行绑定,并为每个复选框添加formControlName
属性,以便与FormGroup中的FormControl对象进行关联。例如:<form [formGroup]="myForm">
<label>
<input type="checkbox" formControlName="checkbox1"> Checkbox 1
</label>
<label>
<input type="checkbox" formControlName="checkbox2"> Checkbox 2
</label>
<label>
<input type="checkbox" formControlName="checkbox3"> Checkbox 3
</label>
</form>
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponentComponent implements OnInit {
myForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.myForm = this.formBuilder.group({
checkbox1: false,
checkbox2: false,
checkbox3: false
});
}
}
this.myForm.patchValue({
checkbox1: true,
checkbox2: true
});
以上代码将会选中checkbox1和checkbox2,而checkbox3保持不变。
这样,你就可以在反应式窗体的formGroup中以编程方式选中多个复选框了。
请注意,以上示例是基于Angular框架的,如果你使用的是其他框架或库,具体实现方式可能会有所不同。
领取专属 10元无门槛券
手把手带您无忧上云