Here's a concise directive that automatically applies CSS classes based on Angular form control validation status:
import { Directive, ElementRef, Input, Renderer2 } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
selector: '[appValidationStyle]'
})
export class ValidationStyleDirective {
@Input() appValidationStyle: NgControl;
constructor(private el: ElementRef, private renderer: Renderer2) {}
ngOnInit() {
this.appValidationStyle.statusChanges?.subscribe(() => {
this.updateStyles();
});
}
private updateStyles() {
const control = this.appValidationStyle;
this.renderer.removeClass(this.el.nativeElement, 'is-valid');
this.renderer.removeClass(this.el.nativeElement, 'is-invalid');
if (control.touched || control.dirty) {
if (control.valid) {
this.renderer.addClass(this.el.nativeElement, 'is-valid');
} else {
this.renderer.addClass(this.el.nativeElement, 'is-invalid');
}
}
}
}
Usage:
<input
formControlName="email"
appValidationStyle
[appValidationStyle]="form.get('email')">