我实现了一个包含复选框和一个提交按钮的模式,如下所示。我想验证复选框,因为至少应从复选框中选择一项,并且仅发送选定的项,而不是全部发送。当我提交项目时,我将发送不想要的所有内容。
屏幕截图
TS文件
...
this.form = this.fb.group({
checkArray: this.fb.array([], [Validators.required])
});
}
ngOnInit() {
this.getAllRemarks();
this.myform = this.fb.group({
otherInput: null,
// API key to bind list of items. e.g. [{id:1},{id:2}]
reason: null
});
}
onClose() {
this.dialogbox.close();
this.dataService.filter('Register click');
}
onCheckBoxChanges(e: HTMLInputElement, id: number) {
// get current position of the changes element by ID
const index = this.remarksList.findIndex(_ => _.id === id);
if (!(index > -1)) return;
// const isChecked = this.checkBoxes[index].isChecked;
// this.masterCheckBoxes[index].isChecked = e.checked;
}
onSubmit() {
// assign the changes value for the POST
this.myform.value['reason'] = this.remarksList;
console.log(this.myform.value);
}
...
HTML文件
<h2>Add Comments</h2>
<p>Reasons for declining the inspection</p>
<form [formGroup]="myform" (ngSubmit)="onSubmit()">
<div *ngFor="let check of this.remarksList;">
<label>
<input #el (change)="onCheckBoxChanges(el, check.id)" type="checkbox" [checked]="check.isChecked" />
{{check.comment}}
</label>
</div>
<br> <br>
Other: <input type="text" formControlName="otherInput" />
<br> <br>
<button type="submit">Submit</button>
</form>
为了根据需要验证formGroup,我们可以设置userDefined验证器。在这里,我使用了requireCheckboxesValidator()作为自定义验证器。这可能有效
myCheckboxGroup: new FormGroup({
myCheckbox1: new FormControl(false),
myCheckbox2: new FormControl(false),
}, requireCheckboxesValidator());
export function requireCheckboxesValidator(minRequired = 1): ValidatorFn {
return function validate (formGroup: FormGroup) {
let checked = 0;
Object.keys(formGroup.controls).forEach(key => {
const control = formGroup.controls[key];
if (control.value === true) {
checked ++;
}
});
if (checked < minRequired) {
return {
requireOneCheckboxToBeChecked: true,
};
}return null;
};
}
在提交时,您可以使用过滤器仅获取选定的值
onSubmit() {
// assign the changes value for the POST
this.myform.value['reason'] = this.remarksList.filter(item => item.isChecked);
console.log(this.myform.value);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句