[试图使用反应式表单验证来验证复选框,但是不起作用。应该选择如何验证所有复选框。如果有人帮助我解决此问题?
app.component.html:
<form (ngSubmit)="onSubmit()" novalidate [formGroup]="fg">
<div><input type="text" formControlName="firstName" class="form-control" placeholder="First name"></div>
<div formArrayName="bUnits">
<div *ngFor="let unit of fg.controls.bUnits.controls; let i = index;">
<p>Unit {{ i + 1 }}</p>
<div>
<label>
<input type="checkbox" [formControlName]="i" [value]="businessUnits[i].value">
{{businessUnits[i].name}}
</label>
</div>
</div>
</div>
<button type="submit">Submit</button>
<p>You have selected all checkboxes ::: {{ fg.valid }}</p>
</form>
完整的代码和演示:https://stackblitz.com/edit/angular-custom-form-validation-ugamqr?file=app/app.component.html
您需要调用您的方法来返回ValidatorFn,如下所示:
this.fg = this.fb.group({
firstName: ['Tiep Phan', [Validators.required]],
bUnits: this.fb.array(
this.businessUnits.map(() => this.fb.control('')),
this.allcheckboxesSelect()
)
});
演示:https://stackblitz.com/edit/angular-custom-form-validation-f3wbsn?file=app/app.component.ts
顺便说一句,您可以将方法提取到一个函数中以降低复杂性:
function allcheckboxesSelect(formArray: FormArray) {
const totalSelected = formArray.controls
.map(control => control.value)
.reduce((prev, next) => next ? prev + next : prev, 0);
return totalSelected >= formArray.length ? null : { required: true };
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
fg: FormGroup;
businessUnits: any[] = [];
constructor(private fb: FormBuilder) { }
ngOnInit() {
// do some stub to grab data
this.businessUnits = [
{ name: 'BU 1', value: "1" },
{ name: 'BU 2', value: "2" },
{ name: 'BU 3', value: "3" }
];
this.fg = this.fb.group({
firstName: ['Tiep Phan', [Validators.required]],
bUnits: this.fb.array(
this.businessUnits.map(() => this.fb.control('')),
allcheckboxesSelect
)
});
}
onSubmit() {
console.log(this.fg);
}
}
演示:https://stackblitz.com/edit/angular-custom-form-validation-qr4vtc?file=app/app.component.ts
或使用内置的验证器功能:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl, ValidatorFn, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
fg: FormGroup;
businessUnits: any[] = [];
constructor(private fb: FormBuilder) { }
ngOnInit() {
// do some stub to grab data
this.businessUnits = [
{ name: 'BU 1', value: "1" },
{ name: 'BU 2', value: "2" },
{ name: 'BU 3', value: "3" }
];
this.fg = this.fb.group({
firstName: ['Tiep Phan', [Validators.required]],
bUnits: this.fb.array(
this.businessUnits.map(() => this.fb.control('', Validators.requiredTrue))
)
});
}
onSubmit() {
console.log(this.fg);
}
}
每个控件无效时具有样式的演示:
https://stackblitz.com/edit/angular-custom-form-validation-f1g1j8?file=app/app.component.css