【问题标题】:bind global value into ValidationErrors in angular将全局值绑定到角度的 ValidationErrors
【发布时间】:2021-10-20 07:12:15
【问题描述】:

我尝试将值绑定到 ValidationErrors。

我有这个方法:

  isUniqueEmail(control: FormControl): ValidationErrors {
    if (control.value != null) {
        console.log(control.value)
        if(control.value == this.foundEmail){
          console.log("found one");
          return {isUniqueEmail: true}
        }else{
          return null;
        }
      }
  }

此方法检查 control.value(电子邮件输入)是否等于存储在全局变量 this.foundEmail 中的电子邮件,然后我们有重复的电子邮件。

我的问题是:我可以用这个方法从 foundEmail 中检索数据,因为这个方法是私有的。

此方法位于导出类 exampleComponent 实现 OnInit 内。

错误:ERROR TypeError: Cannot read properties of undefined (reading 'foundEmail')

但我检查我有数据到foundEmail

【问题讨论】:

  • 如果我们正在处理上下文,最好解释一下这个isUniqueEmail函数的位置。这是在课堂上吗?这个 this 是从哪里来的?他是从父函数来的吗?
  • 内部导出类exampleComponent实现OnInit。 @NicolasDellazzeri
  • 另一件事,在 JS 中你不需要检查某个值是否不同于 null。有 truthy 和 falsy 值,这使您的 if(control.value != null) 语句变得多余

标签: javascript angular validation


【解决方案1】:

验证器函数是从FormControl 调用的,因此它的上下文不会绑定到您在其上定义方法的类。您需要手动将isUniqueEmail()绑定到this。

两种选择:

  1. 定义 FormControl 时使用bind():

    name: new FormControl("", [
        this.isUniqueEmail.bind(this),
    ]),
    
  2. 将您的验证器定义为arrow function:

isUniqueEmail = (control: FormControl) => {
    if (control.value != null) {
        console.log(control.value)
        if(control.value == this.foundEmail){
          console.log("found one");
          return {isUniqueEmail: true}
        }else{
          return null;
        }
      }
  }

【讨论】:

  • 太棒了!!!谢谢
猜你喜欢
  • 2019-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 2019-12-06
  • 1970-01-01
  • 2018-05-21
相关资源
最近更新 更多