我有一个基本上是这样的 react 形式。
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 添加一个元素
我总结了 sections formArray
内每个 section
的所有百分比,并验证它不大于 1(我假设用户在这些特定的字段中输入 float )输入)。最后,如果总和大于 1,我想禁用表单末尾的提交按钮。
我尝试了这个问题的答案,但没有成功,因为https://stackoverflow.com/a/48706808/8579973
因为它是针对一组完全相同的对象的。我需要它来验证每个组中的“百分比”元素。
我还尝试将总和存储在本地存储中,但我不想要任何触发该过程的额外按钮。
感谢您的回答, 问候
最佳答案
像这样吗? 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;
}
关于javascript - 验证响应式(Reactive)表单元素的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53438912/