基于值变化的角度条件验证器

问题描述 投票:0回答:1

我正在寻求在电子邮件或电话输入字段中填写必填字段。

例如,当电子邮件输入为空时,电话是必填字段。另一方面,当电话输入为空时,电子邮件是必填字段。

在我的以下代码中,控制台中显示错误“ ERROR TypeError:无法读取null的属性'valueChanges'”

我尝试将两个都拆分为一个单独的函数,但又收到另一条错误消息,说“ RangeError:超出了最大调用堆栈大小”。

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();
        }
    });
angular typescript formgroups
1个回答
0
投票

如您所知,您可以直接在html中使用required验证程序。因此,使其可计算并添加条件。喜欢

<input ... [required]="contactForm.get('phone').length"
© www.soinside.com 2019 - 2024. All rights reserved.