简体   繁体   English

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

[英]Validate sum of reactive form elements

I have a reactive form that is basically this. 我有一个基本的反应形式。

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() is a function that adds an element to my sections FormArray when i click something that's on my template addSection()是一个函数, sections FormArray when i click something that's on my template ,会将元素添加到我的sections FormArray when i click something that's on my template

I sum up all percentages from every section inside the sections formArray and validate that it isn't bigger than 1 (I assume user is typing floating points in those specific inputs). 我总结了sections formArray section每个section所有百分比,并验证它不大于1(我假设用户在那些特定的输入中键入浮点数)。 Finally i want to disable the submit button at the end of the form if the sum if bigger than 1. 最后,如果总和大于1,我想禁用表单末尾的提交按钮。

I tried the answer from this question but didn't work cause https://stackoverflow.com/a/48706808/8579973 cause it was meant for a group of object thats all the same. 我尝试了这个问题的答案,但是没有起作用,原因是https://stackoverflow.com/a/48706808/8579973因为它是针对一组相同的对象的。 I need it to validate just the "percentage" element from every group that is made. 我需要它来验证每个组成的组中的“百分比”元素。

I also tried to store the sum in local storage, but I don't want any extra button that triggers that procedure. 我也尝试将总和存储在本地存储中,但是我不希望任何额外的按钮来触发该过程。

Thanks for your answers, Regards 感谢您的回答,问候

Like this? 像这样? Stackblitz : https://stackblitz.com/edit/angular-vdgdv2 Stackblitzhttps : //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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM