ngFor list不打印空值

时间:2018-05-09 22:15:38

标签: angular ionic-framework ionic2 ionic3

我收到数据(用于卡片),我将其作为列表进一步填充:

[{"id":20,"responsibilities":[{"id":39,"attribute":"Name","action":"","card":20},{"id":40,"attribute":"ISBN","action":"","card":20},{"id":41,"attribute":"Genre","action":"","card":20},{"id":42,"attribute":"","action":"Purchase","card":20}],"collaborators":[],"thing":"Book"}] 

我填写两个列表如下:

   <h6>Attributes</h6>
   <ul>
     <li *ngFor="let item of card.responsibilities">
      <div *ngIf="item.attribute">{{item.attribute}}</div>
    </li>
   </ul>
   <h6>Actions</h6>
   <ul>
     <li *ngFor="let item of card.responsibilities">
       <div *ngIf="item.action">{{item.action}}</div>
     </li>
   </ul>
 </ion-col>

如下所示:

enter image description here

我不想打印具有空值的项目,即如果属性为空字符串“”则在第一个列表中打印,或者如果操作是空字符串“”则在第二个列表中打印。现在这些值也会在两个列表中打印出来。

如何解决这个问题? * ngIf,因为我尝试没有效果。

1 个答案:

答案 0 :(得分:2)

您的*ngIf位于*ngFor元素的<li>内,这意味着它仍会为每个<li>创建一个item of card.responsibilities元素,而{ {1}}如果<div>评估为false,它就不会存在。相反,将item.action放在*ngIf元素本身上,如下所示:

<li>

这样,仅当<ul> <span *ngFor="let item of card.responsibilities"> <li *ngIf="item.action"> {{item.action}} </li> </span> </ul> 评估为<li>时才会创建item.action元素。