Вам нужно вызвать свой метод, чтобы вернуть 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