我想在没有表单标签的情况下对复选框进行验证.应至少选中一个复选框.
<div *ngFor="let item of officeLIST"> <div *ngIf=" item.officeID == 1"> <input #off type="checkBox" id="off" name="off" value="1" [(ngModel)]="item.checked"> <label>{{item.officename}}</label> </div> <div *ngIf="item.officeID== 2"> <input #off type="checkBox" id="off" name="off" value="2" [(ngModel)]="item.checked"> <label>{{item.officename}}</label> </div> <div *ngIf="item.officeID== 3"> <input #off type="checkBox" id="off" name="off" value="3" [(ngModel)]="item.checked"> <label>{{item.officename}}</label> </div> </div>
对于其他领域,我将把所需要的和错误|触摸|有效等等但由于复选框不是单一输入,我不能在每个复选框中放置所需,因为所有复选框都必须被选中.那么如何进行验证以提醒用户至少应检查一个?
解决方法
考虑创建一个包含复选框组的FormGroup,并将组的选中值绑定到带有必需验证器的隐藏formcontrol.
消耗你有三个复选框
items = [ {key: 'item1',text: 'value1'},// checkBox1 (label: value1) {key: 'item2',text: 'value2'},// checkBox2 (label: value2) {key: 'item3',text: 'value3'},// checkBox3 (label: value3) ];
第1步:为您的复选框定义FormArray
let checkBoxGroup = new FormArray(this.items.map(item => new FormGroup({ id: new FormControl(item.key),// id of checkBox(only use its value and won't show in html) text: new FormControl(item.text),// text of checkBox(show its value as checkBox's label) checkBox: new FormControl(false) // checkBox itself })));
*easy to show via ngFor
步骤2:创建隐藏的必需formControl以保持复选框组的状态
let hiddenControl = new FormControl(this.mapItems(checkBoxGroup.value),Validators.required); // update checkBox group's value to hidden formcontrol checkBoxGroup.valueChanges.subscribe((v) => { hiddenControl.setValue(this.mapItems(v)); });
we only care about hidden control’s required validate status and won’t show this hidden control in html.
Step3:创建最终表单组包含下面的复选框组和隐藏的formControl
this.form = new FormGroup({ items: checkBoxGroup,selectedItems: hiddenControl });
Html模板:
<form [formGroup]="form"> <div [formArrayName]="'items'" [class.invalid]="!form.controls.selectedItems.valid"> <div *ngFor="let control of form.controls.items.controls; let i = index;" [formGroup]="control"> <input type="checkBox" formControlName="checkBox" id="{{ control.controls.id.value }}"> <label attr.for="{{ control.controls.id.value }}">{{ control.controls.text.value }}</label> </div> </div> <div [class.invalid]="!form.controls.selectedItems.valid" *ngIf="!form.controls.selectedItems.valid"> checkBox group is required! </div> <hr> <pre>{{form.controls.selectedItems.value | json}}</pre> </form>
参考这个demo.