选中所有复选框反应形式 角度 8



我的复选框表单中有多个复选框数组。当用户单击全选按钮时,我需要选中所有复选框。通过使用reactive formsFormArray这是我尝试过的:

Ts文件

get formReceivedSummons() {
return this.form.get('receivedSummons') as FormArray;
}
formReceivedSummonsItems(i: number) {
return (this.formReceivedSummons.controls[i].get('items')) as FormArray;
}
constructor(private inquiryStore: InquiryStoreService, private formBuilder: FormBuilder) { }
ngOnInit() {
this.form = this.formBuilder.group({
receivedSummons: this.formBuilder.array([])
});
this.getReceivedSummons();
}
getReceivedSummons() {
this.inquiryStore.summons$.subscribe(result => {
this.receivedSummon = result;
this.addCheckboxes();
});
}
selectAllCheckbox() {
this.formReceivedSummons.controls.map(value => value.setValue(true));
}
addCheckboxes() {
this.formReceivedSummons.setValue([]);
this.receivedSummon.data.items.map(x => {
const group = this.formBuilder.group({
header: [this.receivedSummon.header],
items: this.formBuilder.array([], [minSelectedCheckboxes(1)])
});
(group.get('items') as FormArray).push(this.formBuilder.group({
name: [x.itemNo],
isChecked: [false, Validators.required]
}));
this.formReceivedSummons.push(group);
});
}

网页文件

<form [formGroup]="form" (ngSubmit)="submitSelectedCheckboxes()">
<ng-container formArrayName="receivedSummons" *ngFor="let summon of formReceivedSummons.controls; let i = index">
<ng-container [formGroup]="summon">
<ng-container formArrayName="items" *ngFor="let item of formReceivedSummonsItems(i).controls; let j = index">
<ng-container [formGroup]="item">
<input type="checkbox" formControlName="isChecked"> {{item.value.name}}
</ng-container>
</ng-container>
</ng-container>
</ng-container>
<br>
</form>
<button (click)="selectAllCheckbox()">SELECT ALL</button>

尝试全选时出现错误:

错误:必须为名称为"标头"的表单控件提供一个值。

我无法弄清楚错误是什么,可以使用一些指导和建议。

您当前的设置没有意义,为每个复选框都有一个表单数组。您应该将所有复选框粘贴在一个表单数组中。此外,header表单控件到处都是重复的。而是将您的代码更改为具有一次header,以及receivedSummons表单数组中的复选框:

ngOnInit() {
this.form = this.formBuilder.group({
header: [''], // outside formarray
receivedSummons: this.formBuilder.array([])
});
this.getReceivedSummons();
}
getReceivedSummons() {
this.inquiryStore.summons$.subscribe(result => {
this.receivedSummon = result;
this.addCheckboxes();
this.isShowResponse = true;
});
}
addCheckboxes() {
this.form.get('header').setValue(this.receivedSummon.header)
this.receivedSummon.data.items.map(x => {
this.formReceivedSummons.push(
this.formBuilder.group({
name: x.itemNo,
isChecked: false
}))
});
}

然后在模板中进行更改,删除内部表单数组:

<form [formGroup]="form" (ngSubmit)="submitSelectedCheckboxes()">
<ng-container formArrayName="receivedSummons" *ngFor="let summon of formReceivedSummons.controls; let i = index">
<ng-container [formGroupName]="i">
<input type="checkbox" formControlName="isChecked"> {{summon.value.name}}
</ng-container>
</ng-container>
</form>

最后是selectAll复选框,像你一样使用map,但访问isChecked表单控件:

selectAll() {
this.formReceivedSummons.controls.map(value => value.get('isChecked').setValue(true));
}

最后你的分叉堆栈闪电战

相关内容

  • 没有找到相关文章

最新更新