2

I have an an async validator on a zip field:

zip: ['', {
            validators: [
              Validators.required,
              Validators.minLength(5),
              Validators.maxLength(5)
            ],
            asyncValidators: [
              adPostFormValidators.isValidZip(this.locationService)
            ]
          },
      ],

However, the field doesn't seem to reflect the error that comes from the async validator until I click out of the field. For example, this is before I click out (the null is the field's error state):

enter image description here

I know that the async validator has run because I output its results into the console:

enter image description here

Then, when I click out or lose focus, the error state is now accurate:

enter image description here

However, the validator was not run again, as nothing new was logged into the console.

2
  • Did you ever find a solution / the cause of this? Commented Jun 28, 2018 at 9:53
  • Just added my answer. Hope it helps :) Commented Jun 28, 2018 at 21:06

1 Answer 1

6

So it seems that because I'm using ChangeDetectionStrategy.OnPush, I had to manually mark async validators for check:

ref.markForCheck()
return { 'Is not a valid zip': { value: control.value } } as ValidationErrors

where ref is of type ChangeDetectorRef.

Sign up to request clarification or add additional context in comments.

2 Comments

Exactly what I was looking for. I had to implement it like here to get it working: github.com/angular/angular/issues/13200#issuecomment-410539106
And this solution looks even simpler, probably more closer to what you did: codesandbox.io/s/m430q31xpx (though pusing ChangeDetectorRef into the validatorFn feels kind of less clean)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.