TS2531 Object is possibly 'null' on basic component example ; avoiding "?" or "!" possible?

Viewed 105

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

<form class="form-horizontal" [formGroup]="bookForm" (ngSubmit)="onSubmit()">
  <div class="form-group has-success has-feedback">
      <div class="col-sm-2">
          <label class="control-label" for="titre">Title</label>
      </div>
      <div class="col-sm-10">
          <input type="text" class="form-control" id="title" placeholder="Type in the title" name="title" formControlName="title" required>
          <div *ngIf="title.invalid && (title.dirty || title.touched)" class="alert alert-danger">
              <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" class="btn btn-default">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 :-/

Any advice is welcomed !!

2 Answers

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')!;
}

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)" class="alert alert-danger">
    <div *ngIf="title?.errors?.['required']">
        Title mandatory
    </div>
    <div *ngIf="title?.errors?.['minlength']">
        Title more than 4 car
    </div>
</div>
Related