'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 1:[1]

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.

Solution 2:[2]

It seems that you have gonna wrong with the formControlName, either it is not added in .ts file or by mistake you have mentioned 'firstName' in the error span

  1. Replace firstName with userName in the error span

Please replace this code -

<span *ngIf = "loginForm.get('firstName').errors?.required">
    Please Enter User Name.
  </span>

With

<span *ngIf = "loginForm.get('userName').errors?.required">   // Here is the change
    Please Enter User Name.
  </span>

Solution 3:[3]

OMG, one hour working on it, realized I had

this.ContactInfoFG.get('phoneNumberFG') as FormGroup;

instead of

this.contactInfoFG.get('phoneNumberFG') as FormGroup;

Just check the characters for this issue nothing else!

Your solutions helped as well.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pooja Mule
Solution 2 Omkar Jadhav
Solution 3 Reza Taba