title: Expression has changed after it was checked in Angular using Reactive Forms
body: <p>I'm doing a web application in Angular 6 and I'm using Reactive Forms. I have a Form Group with an array and I am setting the values in <code>ngOnInit</code>. I have a custom validator to know if the field called <code>id</code> is unique.</p>
  
  <pre><code>officesFormGroup: FormGroup;
  
  constructor(private fb: FormBuilder) {
      this.officesFormGroup = this.fb.group({
        offices: this.fb.array([], Validators.required)
      });
    }
  
  ngOnInit() {
        this.setOffices();
    }
  
  setOffices() {
      const control = this.officesForm;
  
      this.company.offices.forEach((office, index) =&gt; {
        control.push(this.fb.group({
          id: office.id,
          name: office.name,
          address: office.address,
          services: this.fb.array([], Validators.required)
        }, {validator: this.officeValidator.bind(this)}));
    }
  
  officeValidator(control: AbstractControl) {
      const id = control.get('id').value;
  
      if (id !== null &amp;&amp; id !== '') {
        const offices: Office[] = this.officesForm.value;
  
        const isIdUnique = offices.map(office =&gt; office.id)
          .some(value =&gt; value === id);
  
        if (isIdUnique) {
          control.get('id').setErrors({unavailable: true});
        } else {
          control.get('id').setErrors(null);
        }
      }
    }
  
  get officesForm() {
      return this.officesFormGroup.get('offices') as FormArray;
    }
  </code></pre>
  
  <p>To add a new office to the array:</p>
  
  <pre><code>addOffice() {
      const office = this.fb.group({
        id: [null, Validators.required],
        name: [null, Validators.required],
        address: [null, Validators.required],
        services: this.fb.array([], Validators.required)
      }, {validator: this.officeValidator.bind(this)});
  
      this.officesForm.push(office);
    }
  </code></pre>
  
  <blockquote>
    <p>ExpressionChangedAfterItHasBeenCheckedError: Expression has changed
    after it was checked. Previous value: 'ngIf: false'. Current value:
    'ngIf: true'.</p>
  </blockquote>
  
  <p>When the page is loaded for the first time, the field called <code>id</code> appears red, like it has errors, which is wrong. It should check for unique if the user adds another office and writed something in the <code>id</code> field.</p>
  
  <p>My goal is, if the user adds a new office or try to edit the <code>id</code> of an existing office, check if the <code>id</code> is unique, I mean, if no other office has the same <code>id</code>.</p>