I have been struggling to pass a class property in a custom async validator, as its value always shows up as undefined
whenever I log it from this validator...
Here is the code snippet from CustomValidators.js :
static isValidPlace(place: Place, controlName: string): AsyncValidatorFn {
return (control: FormControl): Observable<{ [key: string]: boolean }> => {
console.log('control', control.value);
console.log('place', place);
if (place && place.label !== control.value)
return Observable.of({ 'invalidPlace': true });
return Observable.empty();
}
}
In the component :
city: FormControl = this.fb.control(
'',
Validators.required,
CustomValidators.isValidPlace(this.citySelection, 'city').bind(this)
);
I have also attached a (change) event on the field which triggers the following function :
onSelectionCity = (selection: Place): Place => this.citySelection = selection;
The question is: How can I update and pass the citySelection
property through my custom validator ?
What I am trying to achieve :
I require an id that is sent by an API when the user clicks on a result list, based on the value typed in a formControl (input).
The issue lies in validating the input field when the user changes the value. The only way to validate the input field is by clicking on a list to get an id. If the value changes, the previously obtained id becomes invalid, and I need to reflect this behavior.
For example, consider a slightly different Google search engine with the conventional "search" button. When you type something into the search field and a list of items appears. Upon clicking on one of the items...
Now, imagine that the button requires an id to fetch the correct information, and this id is obtained upon click events.
You have your id, but if you change the text, the input field should become invalid because the previous id no longer matches the potential search request.
My suggestion is to compare the entire object, including label, id, and other properties saved in the selectionCity
property within my component class during click events with the current value of the formControl. This will allow us to determine validity through a simple triple comparison.