title: Angular - assign custom validator to a FormGroup
body: <p>I need to assign a custom validator to a FormGroup. I can do this at the time the FormGroup is created like this:</p>
  
  <pre><code>let myForm : FormGroup;
  
  myForm = this.formBuilder.group({
          myControl1: defaultValue,
          myControl2: defaultValue
        }, { validator: this.comparisonValidator })
  
  comparisonValidator(g: FormGroup) {
        if (g.get('myControl1').value &gt; g.get('myControl2'.value)) {
          g.controls['myControl1'].setErrors({ 'value2GreaterThanValue1': true });
          return;
        }
  }
  </code></pre>
  
  <p>I have a situation though where I need to add the custom validator <em>after</em> I've instantiated the FormGroup, so I'm trying to do this after instantiating <code>myForm</code>, instead of adding the validator when the form is instantiated:</p>
  
  <pre><code>let myForm : FormGroup;
  
  myForm = this.formBuilder.group({
          myControl1: defaultValue,
          myControl2: defaultValue
        })
  
  this.myForm.validator = this.comparisonValidator;
  </code></pre>
  
  <p>This gives me a compiler error:</p>
  
  <pre><code>Type '(g: FormGroup) =&gt; void' is not assignable to type 'ValidatorFn'.
    Type 'void' is not assignable to type 'ValidationErrors'.
  </code></pre>
  
  <p>How do I assign a validator to my <code>FormGroup</code> so that the <code>formGroup</code> is passed as the argument to my <code>comparisonValidator</code> function?</p>
  
  <p><strong>Update</strong> - I've added a line showing where I'm doing a <code>setErrors</code> in my <code>comparisonValidator</code>, to make it clearer exactly how I'm trying to set a validation error.</p>