获取对象可能为"null".在Angular模板文件中

编程入门 行业动态 更新时间:2024-10-28 04:24:52
本文介绍了获取对象可能为"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模板文件中

本文发布于:2023-10-22 22:11:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1518873.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:能为   对象   模板   文件   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!