Home > Software engineering >  TS2531 Object is possibly 'null' on basic component example and no Validators fired
TS2531 Object is possibly 'null' on basic component example and no Validators fired

Time:05-03

I've setup this basic component with npm 8.3.1/node 16.14.0/angular 13.3.4 :

<form  [formGroup]="bookForm" (ngSubmit)="onSubmit()">
  <div >
      <div >
          <label  for="titre">Title</label>
      </div>
      <div >
          <input type="text"  id="titre" placeholder="Type in the title" name="titre" required>
          <div *ngIf="title.invalid && (title.dirty || title.touched)" >
              <div *ngIf="title.errors?.['required']">
                  Title mandatory
              </div>
              <div *ngIf="title.errors?.['minlength']">
                  Title more than 4 car
              </div>
          </div>
      </div>
  </div>
  <button type="submit" >Submit</button>
</form>

and a such sample compoment :

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

@Component({
  selector: 'app-book-form',
  templateUrl: './book-form.component.html'
})
export class BookFormComponent implements OnInit {

  bookForm: FormGroup = new FormGroup(
    {
      title: new FormControl('', [
        Validators.required,
        Validators.minLength(4)
      ])
    },
  );

  constructor( private formBuilder: FormBuilder, private router: Router) {}

  ngOnInit(): void {}
  
  get title() {
    return this.bookForm.get('title');
  }

  onSubmit() {
    return false;
  }
}

Why does the hell can I've got this error on *ngIf="title statements ?

error TS2531: Object is possibly 'null'.

Pushed in StackBlitz, I don't have this error :-/ But I don't get the validator working either :(

Any advice is welcomed !!

CodePudding user response:

Try adding exclamation mark ! at the end of the getter, with this, you are telling Typescript you are assuring the getter title will return a value different than null/undefined

get title() {
 return this.bookForm.get('title')!;
}

CodePudding user response:

Generally this.bookForm.get may return undefined. So Typescript assumes title is possibly undefined. You have to replace title. to title?..

<div *ngIf="title?.invalid && (title?.dirty || title?.touched)" >
    <div *ngIf="title?.errors?.['required']">
        Title mandatory
    </div>
    <div *ngIf="title?.errors?.['minlength']">
        Title more than 4 car
    </div>
</div>
  • Related