title: How can I manually set an Angular form field as invalid?
body: <p>I am working on a login form and if the user enters invalid credentials we want to mark both the email and password fields as invalid and display a message that says the login failed. How do I go about setting these fields to be invalid from an observable callback?</p>
  
  
  
  <p>Template:</p>
  
  <pre class="lang-html prettyprint-override"><code>&lt;form #loginForm="ngForm" (ngSubmit)="login(loginForm)" id="loginForm"&gt;
    &lt;div class="login-content" fxLayout="column" fxLayoutAlign="start stretch"&gt;
      &lt;md-input-container&gt;
        &lt;input mdInput placeholder="Email" type="email" name="email" required [(ngModel)]="email"&gt;
      &lt;/md-input-container&gt;
      &lt;md-input-container&gt;
        &lt;input mdInput placeholder="Password" type="password" name="password" required [(ngModel)]="password"&gt;
      &lt;/md-input-container&gt;
      &lt;p class='error' *ngIf='loginFailed'&gt;The email address or password is invalid.&lt;/p&gt;
      &lt;div class="extra-options" fxLayout="row" fxLayoutAlign="space-between center"&gt;
       &lt;md-checkbox class="remember-me"&gt;Remember Me&lt;/md-checkbox&gt;
        &lt;a class="forgot-password" routerLink='/forgot-password'&gt;Forgot Password?&lt;/a&gt;
      &lt;/div&gt;
      &lt;button class="login-button" md-raised-button [disabled]="!loginForm.valid"&gt;SIGN IN&lt;/button&gt;
       &lt;p class="note"&gt;Don't have an account?&lt;br/&gt; &lt;a [routerLink]="['/register']"&gt;Click here to create one&lt;/a&gt;&lt;/p&gt;
     &lt;/div&gt;
   &lt;/form&gt;
  </code></pre>
  
  <p>Login method:</p>
  
  
  
  <pre class="lang-ts prettyprint-override"><code> @ViewChild('loginForm') loginForm: HTMLFormElement;
  
   private login(formData: any): void {
      this.authService.login(formData).subscribe(res =&gt; {
        alert(`Congrats, you have logged in. We don't have anywhere to send you right now though, but congrats regardless!`);
      }, error =&gt; {
        this.loginFailed = true; // This displays the error message, I don't really like this, but that's another issue.
        this.loginForm.controls.email.invalid = true;
        this.loginForm.controls.password.invalid = true; 
      });
    }
  </code></pre>
  
  <p>In addition to setting the inputs invalid flag to true I've tried setting the <code>email.valid</code> flag to false, and setting the <code>loginForm.invalid</code> to true as well. None of these cause the inputs to display their invalid state.</p>