Getting Object is possibly 'null'. in Angular template file

Viewed 10377

In my Angular app, I'm getting the following error:

Object is possibly 'null'.

The problem is that I'm getting this error not because of some typescript code, but because of this html template:

  <form [formGroup]="form">
    <timepicker [formControlName]="'myControl'"></timepicker>
  </form>

  <br>
  <button class="btn btn-succes" (click)="form.get('myControl').enable()">Enable Control</button>
  <button class="btn btn-warning" (click)="form.get('myControl').disable()">Disable Control</button>
  <br><br>

  <pre class="alert alert-info">Time is: {{ form.get('myControl').value }}</pre>
3 Answers

This error comes when the flag --strictNullChecks is enabled and to solve it, it's needed to check if one object is not null before accessing its properties.

For example, in this case:

<button (click)="form.get('myControl').enable()"></button>

we first need to check that the form object is not null, before calling get(...) on it:

<button *ngIf="form" (click)="form.get('myControl').enable()"></button>

alternatively, one can wrap more html elements in one <ng-container> to avoid repetition of ngIfs:

<ng-container *ngIf="form">
  <form [formGroup]="form">
    <timepicker [formControlName]="'myControl'"></timepicker>
  </form>

  <br>
  <button class="btn btn-succes" (click)="form.get('myControl').enable()">Enable Control</button>
  <button class="btn btn-warning" (click)="form.get('myControl').disable()">Disable Control</button>
  <br><br>

  <pre class="alert alert-info">Time is: {{ form.get('myControl').value }}</pre>
</ng-container>

FWIW, you could also encapsulate the form-control access in a getter, together with an explicit type conversion:

get myControl() {return this.form.get('myControl') as FormControl;}

This would avoid the error, plus it makes the template DRYer.

on tsconfig.json I set the strictTemplates to false

  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": false
  }
Related