代码之家  ›  专栏  ›  技术社区  ›  sebaLinares

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

  •  0
  • sebaLinares  · 技术社区  · 7 年前

    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: '',
        }));
      }
    

    sections FormArray when i click something that's on my template

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

    我尝试了这个问题的答案,但没有成功 https://stackoverflow.com/a/48706808/8579973

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

    当做

    1 回复  |  直到 7 年前
        1
  •  4
  •   zer0    7 年前

    这样地? 闪电战 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;
    }
    
    推荐文章