My input is defined as shown below
<input
id="xInputControl"
name="xInputControl"
type="text"
xInput
class="form-control"
[(ngModel)]="x"
#validated="ngModel"
(ngModelChange)="valueChanged()"
/>
I have implemented a custom validator for the input field
@Directive({
selector: '[xInput]',
providers: [
{
provide: NG_VALIDATORS,
useExisting: LatestXInputValidatorDirective,
multi: true,
},
],
})
export class LatestXInputValidatorDirective implements Validator {
validate(control: AbstractControl): ValidationErrors | null {
if (
control.value === undefined ||
control.value === null ||
control.value === ''
) {
return { emptyInput: 'dummy text' };
} else if (
control.value.indexOf(',') > 0 ||
control.value.indexOf('.') > 0
) {
return { decimalNumber: control.value };
} else {
const parsed = parseInt(control.value);
if (isNaN(parsed)) return { notANumber: control.value };
else if (parsed > 200) return { overLimits: control.value };
else if (parsed < 1) return { negativeNumber: control.value };
else if (parsed === 1) return { useLatestAggregation: control.value };
// The value is valid
else return null;
}
}
}
Referencing this documentation
The ngModel will be set only when input validation passes. For example, email inputs must follow the format user@domain
Also read more on this page
By default, ngModel sets the model value to undefined for invalid input values.
I expect the ngModelChange
method in the HTML input to be called only when the input has a valid value that passes the LatestXInputValidatorDirective
validation.
Unfortunately, this is not happening. The
(ngModelChange)="valueChanged()
function is triggered after every keystroke. I can verify this through the following method
valueChanged() {
console.warn('The current value of x is ', this.x);
...
}
I see logs appearing in the console with each keystroke
How can I ensure that valueChanged
is only invoked when the input contains a VALID value that clears the validation from LatestXInputValidatorDirective
?