validation - Angular 2 Custom Validator with Observable Parameter -


i have custom validator:

export const mealtypesvalidator = (mealselected: boolean) => {     return (control: formcontrol) => {         var mealtypes = control.value;         if (mealtypes) {             if (mealtypes.length < 1 && mealselected) {                 return {                     mealtypesvalid: { valid: false }                 };             }         }         return null;     }; }; 

if use works:

ngoninit() {     this.findform = this.formbuilder.group({         categories: [null, validators.required],         mealtypes: [[], mealtypesvalidator(true)],         distancenumber: null,         distanceunit: 'kilometers',         keywords: null,     }); } 

the catch is, mealselected property on component - changes when user selects , deselects meal.

how call validator above using static true can never change.

how can validator work when use component.mealselected value parameter eg:

ngoninit() {     this.findform = this.formbuilder.group({         categories: [null, validators.required],         mealtypes: [[], mealtypesvalidator(this.mealselected)],         distancenumber: null,         distanceunit: 'kilometers',         keywords: null,     }); } 

because if above, evaluates this.mealselected instantly false @ time - , when user selects meal, doesn't go ahead , pass true custom validator.

solution move validator inside component , use this.mealselected check against. had issue validator not being triggered when meal selected/deselected , used this.findform.controls['mealtypes'].updatevalueandvalidity(); trigger validation.

code (can refactored remove parameter custom validator):

ngoninit() {     this.findform = this.formbuilder.group({         categories: [null, validators.required],         mealtypes: [[], this.mealtypesvalidator(true)],         distancenumber: null,         distanceunit: 'kilometers',         keywords: null,     }); }  mealtypesvalidator = (mealselected: boolean) => {     return (control: formcontrol) => {         var mealtypes = control.value;         if (mealtypes) {             if (mealtypes.length < 1 && this.mealselected) {                 return {                     mealtypesvalid: { valid: false }                 };             }         }         return null;     }; }; 

however still nice able have seperate validation module centralise validation, if knows how have changing parameter value such component field parameter custom validator - asked, i'd appreciate answer goes technique.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -