Created
October 14, 2019 12:54
-
-
Save fabriciobastian/08963aada51c22ea4b90bc97d8317a62 to your computer and use it in GitHub Desktop.
Angular validation directive for template-driven forms
This file contains hidden or 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, Input, OnChanges, SimpleChanges } from '@angular/core'; | |
import { NG_VALIDATORS, Validator, AbstractControl, ValidationErrors } from '@angular/forms'; | |
@Directive({ | |
selector: '[greaterThan]', | |
providers: [ | |
{ | |
provide: NG_VALIDATORS, | |
useExisting: GreaterThanValidator, | |
multi: true, | |
}, | |
], | |
}) | |
export class GreaterThanValidator implements Validator, OnChanges { | |
@Input() public greaterThan: number; | |
private _onChange: () => void; | |
validate(control: AbstractControl): ValidationErrors | null { | |
if (this.greaterThan <= control.value) { | |
return null; | |
} | |
return { 'greaterThan': true }; | |
} | |
registerOnValidatorChange(fn: () => void): void { | |
this._onChange = fn; | |
} | |
ngOnChanges(changes: SimpleChanges): void { | |
if ('greaterThan' in changes) { | |
if (this._onChange) { | |
this._onChange(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment