繁体   English   中英

如何在 ngFor 循环中使用 ngIf 循环?

[英]how can i use a ngIf cycle inside a ngFor cycle?

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

<ng-template pTemplate="body" ngFor let-car [ngForOf]="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-template>

它不起作用

你有 go:

<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>

您可以在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>

此代码必须有效:

<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>

暂无
暂无

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

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