如何在角度6中使用反应形式来验证复选框

时间:2019-09-25 11:04:13

标签: angular6 angular7 angular2-forms

试图使用反应式表单验证来验证复选框,但不起作用。应如何选择所有复选框的验证。如果有人帮助我解决此问题?

1 个答案:

答案 0 :(得分:0)

您需要像下面这样调用您的方法以返回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