【发布时间】:2019-03-27 16:26:01
【问题描述】:
我的 Angular 6 项目中有一个 Form Builder 表单,但我遇到了验证器问题。
我想我知道问题出在哪里,但不知道如何解决。 我有一个自定义验证器(不是真正的自定义,我使用 min() 和 max() 以及自定义变量进行检查)
并且可能在这些值之前初始化表单。
表单在构造函数之前声明(我尝试将其移入构造并移入ngOnInit,结果相同)
myForm = this.fb.group({
title: [""],
date: [""],
max_score: [, [Validators.required, Validators.max(6), Validators.min(1)]],
min_score: [, [Validators.required, Validators.max(6), Validators.min(1)]]
});
constructor(private fb: FormBuilder) {}
像这样一切正常,即使是验证器。
max_score 和 min_score 是 2 个下拉菜单,您可以在其中选择一个数字。
我想要实现的是:
max_score: [, [Validators.required, Validators.max(6), Validators.min(this.myForm.get("min_points").value)]],
min_score: [, [Validators.required, Validators.max(this.myForm.get("max_score").value), Validators.min(1)]]
所以基本上max_score不能低于min_score,min_score不能高于max_score!
但这给了我错误:
TypeError: Cannot read property 'get' of undefined
所以我猜这是因为在初始化表单构建器时无法访问this.myForm.get("max_score").value。
我该如何解决这个问题?这些值在我的表单中是可选的,因此它们在开始时没有值是正确的,我只想进行检查以避免选择高于 max_value 的 min_value
我什至尝试将 this.myForm.get.... 放在一个函数中:
getMaxPoints(): number {
if (this.myForm.get("max_score").value) {
return this.myForm.get("max_score").value;
} else return null;
}
然后
min_score: [, [Validators.required, Validators.max(this.getMaxPoints()), Validators.min(1)]]
但我得到了同样的错误!
解决此问题的方法是什么?
【问题讨论】:
-
这不是
max_score而不是this.myForm.get("max_points").value)同样适用于min_points -
对不起,这只是 stackoverflow 上的一个错字,在我的代码中,它到处都是 max_score!所以不是这样的
标签: javascript angular forms angular6 formbuilder