我们可以使用Angular的FormArray来实现复选框或单选按钮的功能。首先,我们需要在组件中创建FormGroup和FormArray的实例。FormGroup将用于包含所有复选框或单选按钮,而FormArray将用于管理它们的状态。
在组件中,我们可以这样创建FormGroup和FormArray:
import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';
@Component({
selector: 'app-checkbox-radio-example',
template: `
`
})
export class CheckboxRadioExampleComponent {
form: FormGroup;
fruitsArray = ['Banana', 'Apple', 'Mango', 'Grapes'];
gendersArray = ['Male', 'Female'];
constructor() {}
ngOnInit() {
this.form = new FormGroup({
fruits: new FormArray([]),
genders: new FormArray([])
});
this.fruitsArray.forEach(() => {
const control = new FormControl(false);
(this.form.controls.fruits as FormArray).push(control);
});
this.gendersArray.forEach(() => {
const control = new FormControl(false);
(this.form.controls.genders as FormArray).push(control);
});
}
get fruits() {
return this.form.get('fruits') as FormArray;
}
get genders() {
return this.form.get('genders') as FormArray;
}
}
在模板中,我们可以使用ngFor
指令遍历FormGroup中的FormArray,然后对于每个元素创建相应的