验证反应性表单元素的总和

时间:2018-11-22 23:05:18

标签: javascript angular typescript angular6

我的反应形式基本上就是这个。

ngOnInit() {

    this.myForm = this.fb.group({
      sections: this.fb.array([])
    });
  }

  addSection(){
    let section = <FormArray>this.myForm.controls.sections;
    section.push(this.fb.group({
      name: '',
      items: this.fb.array([]),
      percentage: '',
    }));
  }

addSection()是一个将元素添加到我的sections FormArray when i click something that's on my template

的函数

我对section中每个sections formArray的所有百分比求和,并验证它不大于1(我假设用户在这些特定输入中键入浮点数)。最后,如果总和大于1,我想在表单末尾禁用提交按钮。

我尝试了此问题的答案,但没有成功,原因是https://stackoverflow.com/a/48706808/8579973是针对一组相同的对象。我需要它来验证每个组成的组中的“百分比”元素。

我还尝试将总和存储在本地存储中,但是我不希望任何额外的按钮来触发该过程。

感谢您的回答, 问候

1 个答案:

答案 0 :(得分:1)

喜欢吗? Stackblitz https://stackblitz.com/edit/angular-vdgdv2

import { Component} from '@angular/core';
import {FormBuilder, FormControl, FormArray, FormGroup, FormGroupDirective, NgForm, ValidatorFn, Validators} from '@angular/forms';


@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent{
  myForm: FormGroup;
  constructor(private fb: FormBuilder){
    this.myForm = this.fb.group({
      sections: this.fb.array([], CustomValidator.checkPercentageSum)
    });
    this.addSection();
  }

  addSection(){
    let section = this.myForm.get('sections') as FormArray;
    section.push(this.fb.group({
      percentage: 0.2,
    }));
    section.push(this.fb.group({
      percentage: 0.3,
    }));
    section.push(this.fb.group({
      percentage: 1,
    }));

    console.log(this.myForm.valid , this.myForm.get('sections').errors);
    // Output: false {Invalid: true}
  }

}

//Custom Validator
export class CustomValidator {
  static checkPercentageSum(sections: FormArray): ValidationResult {
    if (sections) {
      let sumOfPercentages: number = 0;
      sections['controls'].forEach((sectionItem: FormGroup) => {
        sumOfPercentages = sectionItem['controls'].percentage.value + sumOfPercentages;
      });

      if (sumOfPercentages > 1) {
        return {"Invalid": true};
      }
    }
    return null;
  }
}

export interface ValidationResult {
  [key: string]: boolean;
}