如何在 angular 6 中使用反应式验证复选框

How to validate checkboxes using reactive form in angular 6

尝试使用反应式表单验证来验证复选框而不是working.How验证所有复选框应该selected.If有人帮我解决这个问题吗?

您需要像这样调用 return 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