How to write custom form validator (model-driven) that depends on current component's property value in Angular2

十年热恋 提交于 2019-12-11 05:16:23

问题


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.

My form declaration is:

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

My validation function is:

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

  return null;
}

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?

Thanks,

Harry


回答1:


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)]
});


来源:https://stackoverflow.com/questions/38496816/how-to-write-custom-form-validator-model-driven-that-depends-on-current-compon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!