1

I have done a custom validator which I apply on one of my two input:

<input type="text"
     class="validate"
     [(ngModel)]="foo"
     name="foo"
     ngControl="foo"
     customValidator                                   
     [validatorArg]="blah"
/>

<input type="text"
     class="validate"
     [(ngModel)]="blah"
     name="blah"
/>

The customValidatordepends on the second input. So what I'd like here, would be to trigger the validator on the foo input when I do modified the blah input. Any idea how to do that ? I could do it on ngModelChange

EDIT: My inputs are part of a form which is a FormGroup

0

1 Answer 1

7

It's a bit problematic with template driven forms. I have done it like this

<input name="blah" ... (ngModelChange)="triggerValidation(formObject.controls.foo)">

triggerValidation(control: AbstractControl) {
    control.markAsTouched();
    setTimeout(() => control.updateValueAndValidity(), 0);
}

If you run updateValueAndValidity() synchronously (without timeout), it may use an old value of the "blah" input.

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

2 Comments

Awesome. For the life of me, I could not figure out why my updateValueAndValidity was using an old value. My problem is trying to run a custom validator in a child control when a parent control changes. Sometimes template driven forms are so difficult... In a Reactive form, I could run my validator whenever I want and not have to rely on Angular's rules. Thanks for the solution
I am using a custom validator which I am triggering on submit for just one filed of the form. I am setting a boolean value to false if a query has returned with an error and I am trying to use this boolean to invalidate the field if it is false. However it appears that calling updateValueAndValidity does trigger the validator but sees the old value of the boolean. t this.isValid = err.error.reqState; // set to false control.markAsTouched({ onlySelf: true }); control.updateValueAndValidity() // here its true

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.