Issue
I can validate form by the help of FormBuilder and FormControl like below
this.pricePerHour = false/true; //based on visible or not
this.myForm = this.formBuilder.group({
Description: new FormControl('', Validators.required),
PerHour: new FormControl('', Validators.compose([this.PriceValidator(this.pricePerHour)]))
//this.pricePerHour is a boolean variable, initially false
});
priceValidator(argPerHour: boolean): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } | null => {
console.log(argPerHour);
// always false even on true
if (control.value == '' && argPerHour == true) {
return { valid: true };
}
return null;
};
}
Here I want to validate PerHour only if pricePerHour is true.
In this case form is checking PerHour field either pricePerHour is false or true (visible/disable). Means boolean variable pricePerHour is always false inside priceValidator().
I also check with below but did not work:-
this.myForm = this.formBuilder.group({
Description: new FormControl('', Validators.required),
PerHour: new FormControl('', Validators.compose([this.pricePerHour ==
true ? null : Validators.required]))
});
Any suggestion on this.
Solution
This was so simple and I made this so complex. I just add below lines where I was calling change function. Solved :slight_smile:
this.myForm.get('PerHour').clearValidators();
this.myForm.get('PerHour').setValidators([Validators.required]);
this.myForm.get('PerHour').updateValueAndValidity();
Answered By - Deepak Dholiyan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.