在我的 Angular 应用程序中,我收到以下错误:
对象可能为“空”。
问题是我收到此错误不是因为某些打字稿代码,而是因为这个 html 模板:
<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
启用并解决这个问题,需要在访问一个对象的属性之前检查它是否不为空。
例如,在这种情况下:
<button (click)="form.get('myControl').enable()"></button>
我们首先需要检查form
调用之前对象不为空get(...)
on it:
<button *ngIf="form" (click)="form.get('myControl').enable()"></button>
或者,可以将更多 html 元素包装在一个元素中<ng-container>
避免重复 ngIf:
<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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)