import { Directive , forwardRef , Attribute } from '@angular/core' ; import { Validator , AbstractControl , NG_VALIDATORS } from '@angular/forms' ; @ Directive ( { selector : '[validateEqual][formControlName],[validateEqual][formControl],[validateEqual][ngModel]' , providers : [ { provide : NG_VALIDATORS , useExisting : forwardRef ( ( ) => EqualValidator ) , multi : true } ] } ) export class EqualValidator implements Validator { constructor ( @ Attribute ( 'validateEqual' ) public validateEqual , @ Attribute ( 'reverse' ) public reverse ) { } private get isReverse ( ) { if ( ! this . reverse ) { return false ; } return this . reverse === 'true' ; } validate ( control ) { const pairControl = control . root . get ( this . validateEqual ) ; if ( ! pairControl ) { return null ; } const value = control . value ; const pairValue = pairControl . value ; if ( ! value && ! pairValue ) { return null ; } if ( this . isReverse ) { if ( value === pairValue ) { if ( pairControl . errors ) { delete pairControl . errors [ 'validateEqual' ] ; } if ( ! Object . keys ( pairControl . errors ) . length ) { pairControl . setErrors ( null ) ; } } else { pairControl . setErrors ( { validateEqual : true } ) ; } return null ; } else { if ( value !== pairValue ) { return { validateEqual : true } ; } } } }