title: Angular FormArray - Duplicate value validator
body: <p>I'm using Angular 6 with reactive forms. One of the form field is a FormArray which adds controls as the user clicks an Add button.</p>
  
  <p>Within the FormArray, I would like to check whether the FormControl value already exists in the FormArray.</p>
  
  <p>This works fine until the user clicks 'Add' button which resets the previous control error and marks the control as valid although it still has a duplicate value.</p>
  
  <p>This is the function to add control in the form array:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>onAddIPAddress() {
  
    if (( &lt; FormArray &gt; this.tcpudpAppFormGroup.get('ipaddressArray')).length &lt; 8) {
  
      const control = new FormControl(null, Validators.compose([
        Validators.required,
        Validators.pattern(this.ipaddressPattern),
        this.forbiddenIPs.bind(this),
        this.onDuplicateIPFormArray.bind(this)
      ]));
  
  
      ( &lt; FormArray &gt; this.tcpudpAppFormGroup.get('ipaddressArray')).push(control);
  
  
    } else {
      return;
    }
  
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>Then, this is the custom validator code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>onDuplicateIPFormArray(control: FormControl): {
    [s: string]: boolean
  } {
  
    if (
      ( &lt; FormArray &gt; this.tcpudpAppFormGroup.get('ipaddressArray')).length &gt; 1 &amp;&amp;
      !( &lt; FormArray &gt; this.tcpudpAppFormGroup.get('ipaddressArray')).value.includes(null) &amp;&amp;
      ( &lt; FormArray &gt; this.tcpudpAppFormGroup.get('ipaddressArray')).value.indexOf(control.value) !== -1)
  
    {
      console.log(( &lt; FormArray &gt; this.tcpudpAppFormGroup.get('ipaddressArray')).value.indexOf(control.value));
  
      return {
        duplicateIP: true
      };
    }
  
    return null;
  
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p>From the console, I can see the IndexOf value is incorrect but not able to understand why.</p>
  
  <p>Any ideas how I can handle this ?</p>
  
  <p>Thanks</p>