1

我正在使用最新的 angular2 表单,并为这个看似简单的任务而苦苦挣扎。我想要一个自定义验证函数,它能够读取当前组件的属性并基于它验证输入。这是示例 plnkr:

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

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

我的表单声明是:

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

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

谢谢,

哈利

4

1 回答 1

0

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

this.loginForm = this.formBuilder.group({
  username: ["", Validators.required],
  password: ["", (control) => this.passwordRequiredForExistingCustomer(control)]
});
于 2016-07-21T06:46:09.683 回答