7

In AngularJS, you could set a input with a directive to delay validation with

link(scope, elem, attr, ngModel) {
    ngModel.$overrideModelOptions({
        updateOn: 'default blur',
        debounce: {
            blur: 0,
            default: 500,
        },
    });
}

What this does is: when the input changes, a 500 millisecond delay is given before the input validates from valid/invalid.

In Angular2+, this seems more difficult. I think I can listen to the changes with observables and update validation that way, but how do I tell the initial input to not validate?

Mike DiDomizio
  • 154
  • 1
  • 10

1 Answers1

12

Since Angular 5.0 have more control on when to run your form validations. You can configure the validations to run either on blur or submit using updateOn options.

  1. Reactive Forms Examples:

Will run validators on form control blur:

new FormControl(null, {
  updateOn: 'blur'
});

Will run validators after the form is submitted:

new FormGroup({
  fistName: new FormControl(),
  lastName: new FormControl()
}, { updateOn: 'submit' });
  1. Template Driven Forms:

Will run validators on form control blur:

<input [(ngModel)]="firstName" [ngModelOptions]="{updateOn: 'blur'}">

Will run validators after the form is submitted:

More info in the docs

As someone in the comments mentioned, you can also subscribe to the form value changes stream, but if you are interested in delayed form validation, you should probably be looking into the updateOn property.

Tomasz Kula
  • 16,199
  • 2
  • 68
  • 79
  • 1
    Thanks for the post. It looks like I do need the `updateOn`. I'm guessing this input directive will now require to be wrapped in a FormBuilder component? There's no way to create a formcontrol on itself? – Mike DiDomizio Apr 06 '18 at 18:30