Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object is possibly 'null' in Reactive Forms Angular

I need your help!I am newbie in Angular Reactive Forms and I am trying to make simple form with validation using Angular's Reactive Forms. But I get an error in this part of my code (ngIf directive, property 'invalid'):

<div class="container">
  <form class="card" [formGroup]="form" (ngSubmit)="submit()">
    <h1>Angular Forms</h1>

    <div class="form-control">
      <label>Email</label>
      <input type="text" placeholder="Email" formControlName="email">
      <div
        *ngIf="form.get('email').invalid" 
        class="validation">
      </div>
    </div>

    <div class="form-control">
      <label>Пароль</label>
      <input type="password" placeholder="Пароль" formControlName="password">
      <div class="validation"></div>
    </div>

    <div class="card">
      <h2>Адрес</h2>

      <div class="form-control">
        <label>Страна</label>

        <select>
          <option value="ru">Россия</option>
          <option value="ua">Украина</option>
          <option value="by">Беларусь</option>
        </select>
      </div>

      <div class="form-control">
        <input type="text">
      </div>

      <button class="btn" type="button">Выбрать столицу</button>
    </div>

    <div class="card">
      <h2>Ваши навыки</h2>
      <button class="btn" type="button">Добавить умение</button>
      <div class="form-control">
        <label></label>
        <input type="text">
      </div>
    </div>

    <button class="btn" type="submit" [disabled]="form.invalid">Отправить</button>

  </form>
</div>

TypeScript code:

import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {
  title = 'forms';
  form!: FormGroup;

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

  submit() {
    console.log('Form submitted', this.form);
    const formData = { ...this.form.value };

    console.log('Form Data:', formData);

  }
}

I use Angular 12 and I followed guide on Udemy, so this is very strange, because my mentor's code works correct. I created FromGroup and FormControls, gave them names, so I am really confused about this error. Do you have any ideas how can I fix it?

like image 371
Vladimir Avatar asked Sep 05 '25 16:09

Vladimir


1 Answers

The Object is possibly 'null' error can happen due to strict type checking and can be solved in 2 ways:

  • Either assert that you are absolutely sure that can never be null, by using the ! (not null assertion operator)
  • Use the ? (optional chaining operator) to stop an eventual error from happening in case the object is indeed null

So you can replace the if statement with form.get('email')?.invalid and it should work. A similar question has been asked here.

like image 61
Octavian Mărculescu Avatar answered Sep 07 '25 07:09

Octavian Mărculescu