Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Angular 2, how to setup an asynchronous validator when using template-driven forms?

I've defined a directive for my asynchronous validator:

@Directive({
  selector: '[validatorUsername]',
  providers: [{ provide: NG_ASYNC_VALIDATORS, useExisting: ValidatorUsernameDirective, multi: true }]
})
export class ValidatorUsernameDirective implements Validator {
  validate(c: AbstractControl) {
    let username = c.value;

    return new Promise(resolve => {
      setTimeout(() => {
        if( username === "nemo" ) {
          resolve({
            'taken': true
          })
        } else {
          resolve(null);
        }
      }, 1000);
    });
  }
}

In template, I've applied it as follows:

<input type="text" [(ngModel)]="username" name="username" required validatorUsername>

Then I've applied validation messages from code (not from template), as described in Angular's Cookbook, chapter Form Validation:

export class App implements OnInit {
  @ViewChild('myForm') myForm: NgForm;

  name: string;
  username: string;

  ngOnInit() {
    this.myForm.valueChanges.subscribe(_ => this.onValueChanged());
  }

  onValueChanged() {
    // fill 'formErrors' object
  }

  formErrors = {
    'name': '',
    'username': ''
  };
}

The problem is that onValueChanged() doesn't get called when validator's promise is resolved, thus the validation message for username does not appear. It appears though if you try to edit the name field. What should I do to trigger the update on UI?

Here is the plunker for my code.


References:

  • Angular2 template driven async validator
  • https://angular.io/docs/ts/latest/cookbook/form-validation.html
  • https://netbasal.com/angular-2-forms-create-async-validator-directive-dd3fd026cb45
like image 289
turdus-merula Avatar asked Feb 22 '26 04:02

turdus-merula


1 Answers

You can subscribe to statusChanges event that is fired after calling async validator

this.myForm.statusChanges.subscribe(_=> this.onValueChanged());

Modified Plunker

like image 72
yurzui Avatar answered Feb 25 '26 14:02

yurzui



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!