I have created a custom directive for my email like @Daniel Francisco Sabugal in this thread:
Angular2 - Control Validation on blur
and it works great, however, I need just a small tweek. My submit button should be submitted only if form is valid, so
[disabled]="!form.valid"
is working fine, but... It stays disabled all the way until i click outside the field, even if the email is in a valid state. Can I somehow put in that condition, to enable button while typing IF the email pattern is correct?
The code from the thread above:
@Directive({
selector: '[validate-onblur]',
host: {
'(focus)': 'onFocus($event)',
'(blur)' : 'onBlur($event)'
}
})
export class ValidateOnBlurDirective {
private validators: any;
private asyncValidators: any;
private hasFocus = false;
constructor(public formControl: NgControl) {
}
onFocus($event) {
this.hasFocus = true;
this.validators = this.formControl.control.validator;
this.asyncValidators = this.formControl.control.asyncValidator;
this.formControl.control.clearAsyncValidators();
this.formControl.control.clearValidators();
this.formControl.control.valueChanges
.filter(() => this.hasFocus)
.subscribe(() => this.formControl.control.markAsPending());
}
onBlur($event) {
this.hasFocus = false;
this.formControl.control.setAsyncValidators(this.asyncValidators);
this.formControl.control.setValidators(this.validators);
this.formControl.control.updateValueAndValidity();
}
}
EDIT 1
@JBNizet solved it with this example: