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

拟墨画扇 提交于 2021-01-27 07:40:44

问题


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>

回答1:


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>


来源:https://stackoverflow.com/questions/53942837/getting-object-is-possibly-null-in-angular-template-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!