当试图在Angular中输出数组的内容时,我正在努力从数据库中排除空条目。
<div class="container" *ngFor="let trees of (this.trees || [])"
<li> {{trees.title}} </li>
<li> {{trees.paragraph1}} </li>
<li> {{trees.paragraph2}} </li>
<li> {{trees.paragraph3}} </li>
</div>
例如,如果某个条目没有为paragraph2
填充,我希望跳过该条目。但是,只有空白区域可以打印出来。
我尝试在容器内使用*ngIf="trees != null"
,但不起作用。
有人对此有任何建议吗?
提前谢谢!
答案 0 :(得分:1)
我认为最简单,最干净的方法是首先使用null
在component.ts
文件中排除array.filter()
值:
let arr1 = ['a', 'b', 'c', null];
let arr2 = arr1.filter(i => i !== null); // will be ['a', 'b', 'c']
然后只需使用*ngFor
来遍历component.html
中的干净数组。
您的实现将比您在上面看到的要复杂一些,但是原理是相同的:首先清除组件中的数据,然后让视图成为不受污染的使用者。
答案 1 :(得分:0)
您似乎想要这样的东西:
<div class="container" *ngFor="let tree of (this.trees || [])">
<li *ngIf="tree.title"> {{tree.title}} </li>
<li *ngIf="tree.paragraph1"> {{tree.paragraph1}} </li>
<li *ngIf="tree.paragraph2"> {{tree.paragraph2}} </li>
<li *ngIf="tree.paragraph3"> {{tree.paragraph3}} </li>
</div>
答案 2 :(得分:0)
如果第2段为null,如果要跳过所有四个li,则可以执行以下操作:
<ng-container *ngFor="let tree of trees">
<div class="container" *ngIf="tree.paragraph2">
<li>{{tree.title}} </li>
<li>{{tree.paragraph1}} </li>
<li>{{tree.paragraph2}} </li>
<li>{{tree.paragraph3}} </li>
</div>
</ng-container>
答案 3 :(得分:0)
<ng-container *ngFor="let tree of trees">
<div class="container" *ngIf="tree!=null">
<li>{{tree.title}} </li>
<li>{{tree.paragraph1}} </li>
<li>{{tree.paragraph2}} </li>
<li>{{tree.paragraph3}} </li>
</div>
</ng-container>
also always use trackby while using ngFor so DOM doesn't gets rendered everytime.