title: Why Angular 4 FormGroup custom validator not working?
body: <p>Trying to add custom validator <code>formValidator()</code> on a form group. Depending on some condition I am setting the errors <code>{invalidData: true}</code>. But when the condition is false setting errors to null. The control2 itself has required validator. If I set errors to null, it will also clear the required validator.</p>
  
  <p>Refer the below code,</p>
  
  <pre><code>createReactiveForm(data: any) {
      const formGroup = new FormGroup({
          'control1': new FormControl(data.value1),
          'control2': new FormControl(data.value2, [Validators.required])
      }, this.formValidator());
  }
  
  formValidator(): ValidatorFn {
      return (group: FormGroup): ValidationErrors =&gt; {
          const control1 = group.controls['control1'];
          const control2 = group.controls['control2'];
          if (control1.value === 'ABC' &amp;&amp; control2.value !== 'ABC') {
              control2.setErrors({ invalidData: true });
          } else {
              control2.setErrors(null);
          }
          return;
      };
  }
  </code></pre>
  
  <p>What is the solution for this? Or am I doing anything wrong in the custom validator? Please help. </p>