我有一组来自网络服务的类别:SELECT
*, max(p.time)
FROM
users u
JOIN
ping p
GROUP BY
u.id
,以及包含所选类别的数组:keyExtractor={(item, index) => item + index}
要显示所有复选框,我会:
categories
这很有效。
然后我构建了我的formGroup:
selectedCategories
现在,我需要的输出只是所选类别的ID。
我对链接formBuilder和formGroup感到有点迷茫。
如果我在模板中添加<form [formGroup]="formGroup" (ngSubmit)="onSubmit()">
<div class="row">
<div *ngFor="let category of categories">
<input type="checkbox" class="custom-control-input" [id]="category.id" formControlName="category"
[checked]="categoriesSelected?.includes(category.id)">
<label class="custom-control-label" [for]="category.id">{{ category.name | translate }}</label>
</div>
</div>
</form>
,则在ngOnInit() {
this.categoriesSelected = this.championships.map(championship => championship.category.id);
this.formGroup = this.formBuilder.group({
categories: this.formBuilder.array([{}])
});
}
标记中,所有数据都会消失。
我该怎么做?
答案 0 :(得分:3)
即将结束,您只需将categoriesSelected
传递到this.formBuilder.array()
并进行一些轻微的标记修改即可。在您的组件中:
constructor(private formBuilder: FormBuilder) {
this.myGroup = this.formBuilder.group({
myCategory: this.formBuilder.array(this.categoriesSelected)
});
}
您可以使用ngFor的索引访问单独的categories
数组以标记复选框:
<form [formGroup]="myGroup">
<div *ngFor="let category of myGroup.controls['myCategory'].controls; let i = index">
<input type="checkbox" [formControl]="category">
<label>{{ categories[i].name }}</label>
</div>
Selected: <strong>{{ myGroup.get('myCategory').value }}</strong>
</form>
答案 1 :(得分:0)
带有Angular示例的动态复选框
musicForm: FormGroup;
musicPreferences = [
{ id: 1, genre: 'Pop' },
{ id: 2, genre: 'Rock' },
{ id: 3, genre: 'Techno' },
{ id: 4, genre: 'Hiphop' }
];
this.musicForm.get('selectAll').valueChanges.subscribe(bool => {
this.musicForm
.get('musicPreferences')
.patchValue(Array(this.musicPreferences.length).fill(bool), { emitEvent:
false });
});
this.musicForm.get('musicPreferences').valueChanges.subscribe(val => {
const allSelected = val.every(bool => bool);
if (this.musicForm.get('selectAll').value !== allSelected) {
this.musicForm.get('selectAll').patchValue(allSelected, { emitEvent: false
});
}
});
submit() {
// Filter out the unselected ids
const selectedPreferences = this.musicForm.value.musicPreferences
.map((checked, index) => checked ? this.musicPreferences[index].id : null)
.filter(value => value !== null);
// Do something with the result
}
<form [formGroup]="musicForm" (ngSubmit)="submit()">
<label>
<input type="checkbox" formControlName="selectAll">
Select/Deselect all
</label>
<label formArrayName="musicPreferences" *ngFor="let genre of
musicForm.controls['musicPreferences'].controls; let i = index">
<input type="checkbox" [formControlName]="i">
{{musicPreferences[i].genre}}
</label>
<button>submit</button>
</form>