简体   繁体   English

我的 ngIf Else 在 Angular 6 中没有按预期工作

[英]My ngIf Else is not working as expected in Angular 6

I have this code that should show the data when the variable blockusers is not empty (which works), but should show the Nought, nil, nada, nothing, zero, zilch and zip WHEN it is empty, which does not work... and I can not see the mistake anywhere.我有这个代码应该在变量 blockusers 不为空时显示数据(有效),但应该显示 Nought、nil、nada、nothing、0、zilch 和 zip 当它为空时,这不起作用......我在任何地方都看不到错误。

<div class="col-lg-9" *ngIf="blockusers; else zipZeroResults">
 I'm getting results and I will show them!
</div>
<ng-template #zipZeroResults>
  Nought, nil, nada, nothing, zero, zilch and zip.
</ng-template>

Thanks for your help谢谢你的帮助

You are doing a truthy check on an array which will always return true if the array reference itself is not null or undefined .您正在对数组进行true检查,如果数组引用本身不是nullundefined则该数组将始终返回true It will even return true if the array is empty (no elements).如果数组为空(没有元素),它甚至会返回 true。

Your truthy check should be done on the length of the array.您应该对数组的length进行真实检查。 Then if the array is empty (length = 0) it will evaluate the expression to false which is what you are expecting.然后,如果数组为空(长度 = 0),它会将表达式计算为 false,这正是您所期望的。

*ngIf="blockusers?.length; else zipZeroResults"

This will check on length but not throw an error if the array itself is undefined or null (using the Safe Navigation Operator ).如果数组本身未定义或为空(使用Safe Navigation Operator ),这将检查长度但不会引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM