Moo
Moo

Reputation: 3665

Angular async validator's state not reflected in form field's error state

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.

Upvotes: 2

Views: 1027

Answers (1)

Moo
Moo

Reputation: 3665

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.

Upvotes: 6

Related Questions