Search code examples
htmlangularangular-reactive-forms

Reactive Form (Cannot Read property error of null)


Error: Cannot read property errors of null in form group.

I am creating a reactive form with some validation but i'm getting this error.Below is my whole form control

  <div class="container mt-5">
<form
  [formGroup] = 'loginForm'
  (ngSubmit) = 'onSubmit()'
  >
  <div class="form-group">
    <label>User Name</label>
    <input
      type="text" class="form-control"
      placeholder="Enter User Name"
      formControlName = "userName"
      [ngClass]="{'is-invalid': (
                                  loginForm.get('userName').dirty &&
                                  !loginForm.get('userName').valid
      )}"
      >
    <span class="invalid-feedback">
      <span *ngIf = "loginForm.get('firstName').errors?.required">
        Please Enter User Name.
      </span>
    </span>
  </div>
  <div class="form-group">
    <label>Password</label>
    <input
      type="password"
      class="form-control"
      placeholder="Password"
      formControlName = "password"
      >
  </div>
  <button
    type="submit"
    class="btn btn-primary"
    [disabled] = "!loginForm.valid">Submit</button>
</form>

{{loginForm.valid}}

Solution

  • Looking at your code, the possible reason for this error seems like you are accessing the firstName formcontrol when it is not defined in the loginForm.