Tried to validate checkboxes using reactive form validation but not working.How to validate for all checkboxes should be selected.If anyone help me to resolve this issue?
You need call your method to return ValidatorFn like this:
this.fg = this.fb.group({
firstName: ['Tiep Phan', [Validators.required]],
bUnits: this.fb.array(
this.businessUnits.map(() => this.fb.control('')),
this.allcheckboxesSelect()
)
});
Demo: https://stackblitz.com/edit/angular-custom-form-validation-f3wbsn?file=app/app.component.ts
Btw, you can extract the method into a function to reduce complexity:
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);
}
}
Demo: https://stackblitz.com/edit/angular-custom-form-validation-qr4vtc?file=app/app.component.ts
Or using built-in validator function:
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);
}
}
Demo with style for each control when it invalid:
https://stackblitz.com/edit/angular-custom-form-validation-f1g1j8?file=app/app.component.css