【发布时间】:2020-06-29 06:51:02
【问题描述】:
我正在尝试将兴趣列表显示为复选框并检查它们是否被选中。我在使用 formArray 时遇到了一些麻烦,并试图设置所有内容。目标是遍历兴趣数组中的所有兴趣,并将它们中的每一个显示为一个复选框。这样我就可以为它提供验证。感谢任何回复的人,谢谢!
<div class="row">
<div class="col">
<div *ngFor="let item of getControls(); let i = index">
<input
type="checkbox"
[formControl]="item"
[id]="i"
(change)="checkBoxClicked(item, i)"
/>
{{ item.value }}
</div>
</div>
</div>
interests = [
'Music',
'Technology',
'Sports',
'Art',
'Fashion',
'Gaming',
'Education',
'Business',
];
selectedInterests = [];
createForm() {
this.form = new FormGroup({
projectName: new FormControl(null, {
validators: [Validators.required],
}),
description: new FormControl(null, {
validators: [Validators.required],
}),
interestsArray: new FormArray([]),
});
this.interests.forEach((item) => {
const interest = this.form.controls.interestsArray as FormArray;
const interestFormControl = new FormControl(false);
interest.push(interestFormControl);
});
console.log(this.form);
getControls() {
return (this.form.get('interestsArray') as FormArray).controls;
}
checkBoxClicked(name, index) {
// console.log(document.getElementById(name.value.split('-')[0]));
this.selectedInterests.push(name);
console.log(name);
console.log(this.selectedInterests);
}
【问题讨论】:
标签: angular angular-forms formarray