title: angular4: custom 'equals' validation using valueChanges observable
body: <p>I needed a validation that checks if <code>email</code> equals <code>Email Confirm</code>.
  For this I created a custom validation that looks like</p>
  
  <pre><code>import { AbstractControl, ValidationErrors, FormGroup } from '@angular/forms';
  
  export function ValidateEqual( equals: string ) {
    return ( control: AbstractControl ): ValidationErrors | null =&gt; {
  
      const equalsField = control.root.get( equals )
      if ( equalsField ) {
  
        equalsField.valueChanges.subscribe( value =&gt; {
          console.log( 'observable fired', value );
          // control.updateValueAndValidity( { onlySelf: true  , emitEvent: false } );
        } );
        if ( control.value !== equalsField.value ) {
          return { equals: true };
        }
      }
      return null;
    }
  }
  </code></pre>
  
  <p>and my form looks like </p>
  
  <pre><code>this.loginForm = this.fb.group( {
    password: [ '', [
      Validators.required,
    ] ],
    email: [ '', [
      Validators.required,
      Validators.email,
    ] ],
    emailConfirm: [ '', [
      Validators.required,
      Validators.email,
      ValidateEqual( 'email' ),
    ] ]
  } );
  </code></pre>
  
  <p>So I am passing the field to check equality with as an argument in <code>ValidateEqual()</code>. That works fine.</p>
  
  <p>The following scenario fails:</p>
  
  <p>1)</p>
  
  <p>Email: mattijs@foo.nl</p>
  
  <p>Confirm Email: mattijs@food.nl</p>
  
  <p>*now Confirm email shows an error that it is not equal to `Email'. Correct.</p>
  
  <p>2) </p>
  
  <p>*now I change the <code>email</code> field to match the <code>confirm email</code> field.</p>
  
  <p>Email: mattijs@food.nl</p>
  
  <p>Confirm Email: mattijs@food.nl</p>
  
  <p>*The error on the <code>confirm email</code> field doesn't disappear because it is not aware of any change. </p>
  
  <p>The issue I have is, that I am trying to use the <code>valueChanges</code> observable on the equals field to have the <code>control</code> field to re-validate, but when I enable <code>control.updateValueAndValidity()</code> it is subscribing exponentially on each keypress and the browser will crash. IT does notify the <code>email confirm</code> field to re-validate, so it almost works...almost.</p>
  
  <p>Does anyone have an idea how to only have it subscribe once and make it re-validate the <code>control</code> field without subscribing again (and again...)?</p>