angularjs ng-if检查数组是否为空

efzxgjgh  于 2024-01-05  发布在  Angular
关注(0)|答案(5)|浏览(280)

如果数组中没有项,我使用的API将返回此值

  1. items: []

字符串
如果数组中有元素,则返回如下内容

  1. items: [
  2. {
  3. name: 'Bla'
  4. }
  5. ]


在我的模板中,我相信我需要使用ng-if来根据其中是否有数据来显示/隐藏元素。

  1. <p ng-if="post.capabilities.items"><strong>Topics</strong>: <span ng-repeat="topic in post.capabilities.items">{{topic.name}}</p>


然而,我可能完全偏离了基础,因为这是我第一次在Angular工作,可能有一个更好的方法来做我想做的事情。

nom7f22z

nom7f22z1#

post.capabilities.items仍然会被定义,因为它是一个空数组,如果你检查post.capabilities.items.length,它应该工作正常,因为0是假的。

webghufk

webghufk2#

验证数组的length属性是否大于0

  1. <p ng-if="post.capabilities.items.length > 0">
  2. <strong>Topics</strong>:
  3. <span ng-repeat="topic in post.capabilities.items">
  4. {{topic.name}}
  5. </span>
  6. </p>

字符串
JavaScript中的数组(对象)是truthy值,因此初始验证<p ng-if="post.capabilities.items">的计算结果始终为true,即使数组为空。

6ju8rftf

6ju8rftf3#

要解决null/undefined问题,请尝试使用?运算符检查是否存在:

  1. <p ng-if="post?.capabilities?.items?.length > 0">

字符串

  • 注意,如果有人到这个页面寻找一个 * 离子框架 * 答案,请确保您使用*ngIf
  1. <p *ngIf="post?.capabilities?.items?.length > 0">

f3temu5u

f3temu5u4#

  • 这是解决方案:*
  1. <div *ngIf="post.capabilities.items.length > 0 && post.capabilities.items[0] !== '' "> ..... </div>

字符串
检查post.capabilities.items的长度是否大于零,并确保数组中的第一个项目不是空字符串。这确保了只有当有可用的post.capabilities.items并且列表中的第一个项目不是空字符串时才显示内容。

5t7ly7z5

5t7ly7z55#

根据我的经验,在HTML模板上做这件事被证明是困难的,所以我决定使用一个事件来调用TS上的一个函数,然后检查条件。

  1. emptyClause(array:any) {
  2. if (array.length === 0) {
  3. // array empty or does not exist
  4. this.emptyMessage=false;
  5. }else{
  6. this.emptyMessage=true;
  7. }
  8. }

字符串
HTML

  1. <div class="row">
  2. <form>
  3. <div class="col-md-1 col-sm-1 col-xs-1"></div>
  4. <div class="col-md-10 col-sm-10 col-xs-10">
  5. <div [hidden]="emptyMessage" class="alert alert-danger">
  6. No Clauses Have Been Identified For the Search Criteria
  7. </div>
  8. </div>
  9. <div class="col-md-1 col-sm-1 col-xs-1"></div>
  10. </form>

展开查看全部

相关问题