【发布时间】:2018-04-19 09:59:55
【问题描述】:
我正在尝试创建一个验证器来检查横梁(船的宽度)是否大于长度。在组件中:
this.vesselForm = this.fb.group({
beam: [null, [
Validators.required,
BeamValidators.beamCannotBeGreaterThanLength,
]],
length: [null, Validators.required],
});
在文件 beam.validators.ts 中:
import { AbstractControl, ValidationErrors } from '@angular/forms';
export class BeamValidators {
static beamCannotBeGreaterThanLength(control: AbstractControl): ValidationErrors | null {
const hullLength = control.parent.controls['length'].value;
// const hullLength = 48;
console.log(hullLength);
if ((control.value >= hullLength)) {
return { beamCannotBeGreaterThanLength: true };
} else {
return null;
}
}
}
我无法弄清楚如何从验证器访问长度。该代码编译过去的智能感知,但在浏览器中出现控制台错误:
ERROR TypeError: Cannot read property 'controls' of undefined
at BeamValidators.beamCannotBeGreaterThanLength (beam.validators.ts:6)
程序的其余部分使用测试行可以正常工作 // const hullLength = 48;
【问题讨论】:
标签: angular angular-reactive-forms custom-validators