title: Angular unit testing form validation - control stays untouched
body: <p>I've an Angular component which has form validation. I'm unit testing to make sure it displays an error message if the input is invalid.</p>
  
  <p>But when I try to change the <code>&lt;input&gt;</code> box value, the control's state remains <code>untouched</code> and the error doesn't display.</p>
  
  <p>Here's the code:</p>
  
  <pre><code>&lt;form #zipForm="ngForm"&gt;
  &lt;label&gt;
      &lt;input type="text" id="postalCode" [(ngModel)]="postalCode" #postalCodeElem="ngModel" name="postalCode" [pattern]="validationPattern" required&gt;
      &lt;button type="button" (click)="click(postalCodeElem.value)"&gt;Enroll&lt;/button&gt;
      &lt;div *ngIf="postalCodeElem.invalid &amp;&amp; postalCodeElem.touched"&gt;
      &lt;span id="required-postal-code" *ngIf="postalCodeElem?.errors?.required"&gt;
          zip/postal code is required
      &lt;/span&gt;
      &lt;span id="invalidPostalCode" *ngIf="postalCodeElem?.errors?.pattern"&gt;
          zip postal code is invalid
      &lt;/span&gt;
      &lt;/div&gt;
  &lt;/label&gt;
  &lt;/form&gt;
  </code></pre>
  
  <p>Test file:</p>
  
  <pre><code>it('should show error in case of invalid postal code', () =&gt; {
      const elem: HTMLElement = fixture.nativeElement;
      const inputElem: HTMLInputElement = elem.querySelector('input');
  
      inputElem.value = 'L5L2';
      inputElem.dispatchEvent(new Event('input', { bubbles: true }));
  
      fixture.detectChanges();
  
      const invalidErrorElem: any = elem.querySelector('span');
  
      console.log('elem', elem);
      console.log('invalidErrorElem', invalidErrorElem);
  
      expect(invalidErrorElem).not.toBeNull();
  });
  </code></pre>
  
  <p>I've created a stackblitz to demo the issue: <a href="https://stackblitz.com/edit/angular-testing-45zwkn?file=app%2Fapp.component.spec.ts" rel="nofollow noreferrer">https://stackblitz.com/edit/angular-testing-45zwkn?file=app%2Fapp.component.spec.ts</a></p>
  
  <p>Any idea what am I doing wrong?</p>