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

查看:21
本文介绍了如何编写依赖于 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.

我错过了什么吗?我应该采用哪种方法来完成这项任务?

Am I missing something? Which approach should I take to achieve this task?

谢谢,

哈利

推荐答案

如果 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天全站免登陆