如何编写依赖于Angular2中当前组件的属性值的自定义表单验证器(模型驱动) [英] How to write custom form validator (model-driven) that depends on current component's property value in Angular2

查看:93
本文介绍了如何编写依赖于Angular2中当前组件的属性值的自定义表单验证器(模型驱动)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用最新的angular2表单,并且正在努力完成这项似乎很简单的任务。我希望有一个自定义验证功能,该功能能够读取当前组件的属性并根据该属性验证输入。这是示例plnkr:

I am working with the latest angular2 forms and struggling with this seems-to-be-simple task. I want to have a custom validation function that is able to read the current component's property and validate the input based on that. Here is the example plnkr:

http: //plnkr.co/edit/bNFjNsCfhYjoqKaRZgQU?p=preview

在此示例中,我始终有一个用户名字段和一个密码字段仅当客户是现有客户时才需要。

In this example, I have a username field which is always required, and a password field that will only be needed if the customer is an existing one.

我的表单声明为:

this.loginForm = this.formBuilder.group({
  username: ["", Validators.required],
  password: ["", this.passwordRequiredForExistingCustomer]
});

我的验证功能是:

passwordRequiredForExistingCustomer(control: FormControl): {[key: string]: boolean} {
  let val = control.value;
  if (this.state === "existingCustomer" && !val) {
    return {"required": true};
  }

  return null;
}

但是,我无法在验证函数中引用当前组件。如果单击现有客户按钮,则会在控制台中看到错误,这是触发自定义功能并且找不到 this

However, I'm unable to refer to the current component inside my validation function. If you click "Existing Customer" button, you will see the error in console, that's when the custom function is triggered and it cannot find this.

我错过了什么吗?

谢谢,

Harry

推荐答案

如果 passwordRequiredForExistingCustomer 是当前组件中的方法,则将验证器作为箭头函数传递,以保持范围的 this。

If passwordRequiredForExistingCustomer is a method in the current component pass the validator as arrow function to keep the scope of this.

this.loginForm = this.formBuilder.group({
  username: ["", Validators.required],
  password: ["", (control) => this.passwordRequiredForExistingCustomer(control)]
});

这篇关于如何编写依赖于Angular2中当前组件的属性值的自定义表单验证器(模型驱动)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆