I was trying to call setErrors()
inside a ngModelChange handler in a template form. It did not work until I waited one tick with setTimeout()
:
template:
<input type="password" [(ngModel)]="user.password" class="form-control"
id="password" name="password" required (ngModelChange)="checkPasswords()">
<input type="password" [(ngModel)]="pwConfirm" class="form-control"
id="pwConfirm" name="pwConfirm" required (ngModelChange)="checkPasswords()"
#pwConfirmModel="ngModel">
<div [hidden]="pwConfirmModel.valid || pwConfirmModel.pristine" class="alert-danger">
Passwords do not match
</div>
component:
@ViewChild('pwConfirmModel') pwConfirmModel: NgModel;
checkPasswords() {
if (this.pwConfirm.length >= this.user.password.length &&
this.pwConfirm !== this.user.password) {
console.log('passwords do not match');
// setErrors() must be called after change detection runs
setTimeout(() => this.pwConfirmModel.control.setErrors({'nomatch': true}) );
} else {
// to clear the error, we don't have to wait
this.pwConfirmModel.control.setErrors(null);
}
}
Gotchas like this are making me prefer reactive forms.