Created
December 31, 2019 01:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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