【发布时间】:2020-09-23 05:01:44
【问题描述】:
我希望实现电子邮件或电话输入字段的必填字段。
例如,当email输入为空时,phone为必填项。反之,当phone输入为空时,email为必填项。
在我的以下代码中,控制台中显示错误“ERROR TypeError: Cannot read property 'valueChanges' of null”
我尝试将两者都拆分为单独的函数,但我收到另一条错误消息,提示“RangeError: Maximum call stack size exceeded”。
this.contactForm.get(["email", "phone"]).valueChanges.subscribe((data) => {
let emailValue: string = data.email;
let phoneValue: string = data.phone;
if (emailValue == "") {
this.contactForm.controls["phone"].setValidators([Validators.required, Validators.pattern("^[0-9]*$")]);
this.contactForm.controls["phone"].updateValueAndValidity();
} else {
this.contactForm.controls["phone"].clearValidators();
this.contactForm.controls["phone"].updateValueAndValidity();
}
if (phoneValue == "") {
this.contactForm.controls["email"].setValidators([Validators.required, Validators.email]);
this.contactForm.controls["email"].updateValueAndValidity();
} else {
this.contactForm.controls["email"].clearValidators();
this.contactForm.controls["email"].updateValueAndValidity();
}
});
【问题讨论】:
-
您应该创建一个客户验证器并传递您需要检查的值(例如 emailValue 和 phoneValue),请参见以下示例:dzone.com/articles/how-to-create-custom-validators-in-angular
-
您在滥用
FormGroup.prototype.getAPI。它接受一组路径来访问嵌套属性,而不是返回多个控件。此外,如果它确实返回了多个控件,则必须将它们返回到一个没有valueChanges方法的数组或对象中。你需要重新考虑。
标签: angular typescript formgroups