问题
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