Search code examples
angulartypescriptngoninit

Why is angular saying my object can be null when creating in ngOnInit?


Creating a form in the component:

export class LoginPageComponent implements OnInit {

  form!: FormGroup

  constructor() { }

  ngOnInit() {
    this.form = new FormGroup({
      email: new FormControl(null, [Validators.required, Validators.email]),
      password: new FormControl(null, [Validators.required, Validators.minLength(6)]),
    })
  }

}

In html, I perform value input checks

<div *ngIf="form.get('email').touched && form.get('email').invalid" class="validation">
  <small *ngIf="form.get('email').errors.required">Enter Email</small>
  <small *ngIf="form.get('email').errors.email">Enter valid Email</small>
</div>

For every line where the form IDEA occurs, swears

error TS2531: Object is possibly 'null'

I understand that this is due to the fact that the creation of the object takes place in ngOnInit. Put a "?" sign everywhere and IDEA stops swearing:

<div *ngIf="form.get('email')?.touched && form.get('email')?.invalid" class="validation">
  <small *ngIf="form.get('email')?.errors.required">Enter Email</small>
  <small *ngIf="form.get('email')?.errors.email">Enter valid Email</small>
</div>

But how correct is it?

Maybe there is a more correct solution to this problem?

Maybe I'm creating the Form Group object incorrectly?


Solution

  • There is nothing logically wrong with the code for checking the control validations using the safe navigation operator, as it has been in TypeScript since version 3.7.

    One other thing I noticed is the repeated gets for the controls in the HTML.

    Move the repeated this.form.get(..) calls into getters like below:

    get email() {
      return this.form.get('email');
    }
    
    get password() {
      return this.form.get('password');
    }
    

    and the HTML script will be tidier as shown with the ? operator still consistent:

    <div *ngIf="email?.touched && email?.invalid" class="validation">
      <small *ngIf="email?.errors.required">Enter Email</small>
      <small *ngIf="email?.errors.email">Enter valid Email</small>
    </div>