Skip to content

Instantly share code, notes, and snippets.

@prudnikov
Created December 31, 2019 01:03
Show Gist options
  • Save prudnikov/030e9861784d9f1ce7c752fb307063ad to your computer and use it in GitHub Desktop.
Save prudnikov/030e9861784d9f1ce7c752fb307063ad to your computer and use it in GitHub Desktop.
This directive will automatically add `is-valid` or `is-invalid` class to the form controls depending on its validity status #angular
import { Directive, ElementRef, HostBinding, OnDestroy, OnInit } from '@angular/core';
import { AbstractControl, NgControl } from "@angular/forms";
import { Subscription } from "rxjs";
@Directive({
selector: '[formControl], [formControlName]',
})
export class ControlValidityClassDirective implements OnInit, OnDestroy {
@HostBinding('class.is-valid')
isValid = true;
@HostBinding('class.is-invalid')
isInvalid = false;
private subscription: Subscription;
constructor(private controlDir: NgControl) { }
ngOnInit(): void {
const control = this.control;
if (!control) {
console.warn('Unknown control');
} else {
this.subscription = control.statusChanges.subscribe(status => {
this.isValid = status === 'VALID';
this.isInvalid = status === 'INVALID';
});
}
}
ngOnDestroy(): void {
if (this.subscription) this.subscription.unsubscribe();
}
get control(): AbstractControl | null {
return this.controlDir.control;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment