我已经实现了一个模式,其中包含复选框和提交按钮,如下所示。我想验证这些复选框,因为至少有一个应该从复选框中选择一个项,并且只发送所选的项,而不是全部。当我提交的项目,我发送的一切,这不是我想做的。
截图

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>发布于 2020-01-16 09:22:35
为了根据需要验证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);
}发布于 2020-01-16 08:54:02
onSubmit筛选复选框列表,例如this.remarksList.filter(item => item.isChecked)
onSubmit() {
// assign the changes value for the POST
this.myform.value['reason'] = this.remarksList.filter(item => item.isChecked);
console.log(this.myform.value);
}https://stackoverflow.com/questions/59765885
复制相似问题