angular - FormArray 的垂直自定义验证器
问题描述
我希望总数精确到 100。但是这个验证器不起作用。我的代码有什么问题?
export class CustomValidators {
public static verticalTotal(total: number, refControl: string) {
return (control: FormArray): ValidationErrors | null => {
const arrayValue = control.value || [];
let actualTotal = 0;
control.controls.forEach(ctrl => {
actualTotal += +(ctrl.get(refControl).value);
});
return actualTotal !== total ?
{ verticalTotal: true,
message: `Total should be ${total}, not ${actualTotal}`
} : null;
};
}
}
我像这样应用验证器
this.itemForm = this.fb.group({
subsidiaries: this.fb.array([], {
validators: [CustomValidators.verticalTotal(100, 'percent')]
})
}, { validators: [] });
const line = this.fb.group({
'name': ['', []],
'percent': [0, []]
});
(this.itemForm.get('subsidiaries') as FormArray).push(line);
this.itemForm.get('subsidiaries').updateValueAndValidity();
解决方案
谢谢@Eliseo,你是对的。我的代码有效。除了我返回的对象不包含消息的定义。它必须是
{
verticalTotal: { valid: false,
message: `Total should be ${total}, not ${actualTotal}`}
} : null;
而不是我的代码中的内容。这样我就可以在组件模板中设置错误消息。
编辑:我做的另一件事是使用价值,而不是actualTotal += +(ctrl.get(refControl).value);
. 这是编辑的部分
arrayValue.forEach(ctrl => {
actualTotal += +(ctrl[refControl]);
});
推荐阅读
- javascript - 如何更改悬停时的图标颜色?
- json - 使用 JSON_MODIFY(),当名称未知或未指定时,如何将字符串附加到根路径?
- c - 裸机可移植库中的 C99“原子”加载
- xml - 在xml文件中添加变量
- javascript - 在 React 中为不同的环境外化不同的环境变量
- intellij-idea - 如何在 IDEA 中运行两个完整的窗口?(或 WebStorm/PyCharm/PhpStorm...)
- ubuntu - 如何更改默认终端远离 LXTerminal?
- azure - 在 socketio 中间件中验证 Azure AD B2C 令牌
- java - 在java中检查正确的括号问题
- node.js - 将文件从 S3 读入缓冲区