如何在ngFor周期内使用ngIf周期?

时间:2019-11-21 14:28:03

标签: html angular

我必须验证数组是否为空,是否为空,我必须传递一条特殊消息, 那就是我尝试过的:

vol.drop(vol.filter(like='Jan').index)

它不起作用

3 个答案:

答案 0 :(得分:1)

去那里:

<div *ngIf="!cars.length; else list">
  No cars
</div>
<ng-template #list>
  <div *ngFor="let car of cars">
    {{car}}
  </div>
</ng-template>

从技术上讲,您无需执行任何操作,如果有车,ngIf将始终为false,如果没有,ngFor将显示0,因此它们是互斥的。这也将起作用:

<div *ngIf="!cars.length">
  No cars
</div>
<div *ngFor="let car of cars">
  {{car}}
</div>

答案 1 :(得分:1)

您可以先检查数组的长度,然后再在ngFor中渲染它们,并创建后备ng-template以显示没有项目:

<ng-container *ngIf="cars && cars.length > 0; else noCars"> 
    <ng-template pTemplate="body" ngFor let-car [ngForOf]="cars">
        <div style="float: left; width: 153px;"> {{car.driver}} </div>
        <div style="float: left; width: 153px;"> {{car.date1 | momentFormat:'DD/MM/YYYY'}} </div>
        <div style="float: left; width: 153px;"> {{car.date2 | momentFormat:'DD/MM/YYYY'}} </div>
        <div style="float: left; width: 153px;"> {{car.description}} </div>            
    </ng-template>
</ng-container>
<ng-template #noCars>
    <div style="float: left; width: auto;"> 
        Ancora nessuna prenotazione per questo veicolo 
    </div>
</ng-template>

答案 2 :(得分:0)

此代码必须有效:

<ng-container *ngFor="let car of cars;">
    <span *ngIf="cars.lenght==0">
                    <div style="float: left; width: auto;"> Ancora nessuna prenotazione per questo veicolo </div>
                </span>
                <span>
                    <div style="float: left; width: 153px;"> {{car.driver}} </div>
                    <div style="float: left; width: 153px;"> {{car.date1 | momentFormat:'DD/MM/YYYY'}} </div>
                    <div style="float: left; width: 153px;"> {{car.date2 | momentFormat:'DD/MM/YYYY'}} </div>
                    <div style="float: left; width: 153px;"> {{car.description}} </div>
                </span>
  </ng-container>