获取对象可能为"null".在Angular模板文件中 [英] Getting Object is possibly 'null'. in Angular template file

查看:510
本文介绍了获取对象可能为"null".在Angular模板文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Angular应用中,出现以下错误:

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

对象可能为'null'.

Object is possibly 'null'.

问题是我收到此错误不是由于某些打字稿代码,而是由于此html模板:

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>

推荐答案

启用标志-strictNullChecks 并解决此错误时,需要检查一个对象是否不为null在访问其属性之前.

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.

例如,在这种情况下:

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

在调用 get(...)之前,我们首先需要检查 form 对象是否不为空:

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>

或者,可以将更多html元素包装在一个< ng-container> 中,以避免重复ngIfs:

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>

这篇关于获取对象可能为"null".在Angular模板文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆