【问题标题】:How to check if you need to loop over variable如何检查是否需要循环变量
【发布时间】:2018-12-19 14:58:55
【问题描述】:

我有两种不同的响应,一种是我们需要循环对象以显示正确的响应。而另一个我们只显示变量。

我尝试的是ng-if else,但它不起作用。

关于这段代码:

<div *ngFor="let courseTimeslot of course?.timeslots">
     <div *ngIf="courseTimeslot; else timeslot" class="timeslots s-padding-l">
        {{ courseTimeslot.timeslot }}
      </div>
</div>

<ng-template #timeslot *ngIf="course?.timeslots" class="timeslots s-padding-l">{{ course?.timeslots }}</ng-template>

这是正确的做法吗,否则我想听听任何其他选择。

【问题讨论】:

  • ng-if else 只有 1 个条件为真,所以如果你想同时做这两个,你不需要 ng-if。只需使用ng-container 而不是ng-template 并删除else timeslot
  • @penleychan 两者都不是,因为在一个页面上我需要显示 if 而在另一页面上显示 else 语句
  • 到目前为止,如果courseTImeslotnull,它将显示您的模板timeslot。我很困惑你所说的2个单独的页面是什么意思?上面的代码是不是包含在同一个组件中?

标签: angular ionic3


【解决方案1】:

可以检查对象是否为数组

<div *ngIf="Array.isArray(course?.timeslots)">
    <div *ngFor="let courseTimeslot of course?.timeslots">
        <div *ngIf="courseTimeslot" class="timeslots s-padding-l">
            {{ courseTimeslot.timeslot }}
        </div>
    </div>
</div>
<div *ngIf="!Array.isArray(course?.timeslots)">
    <ng-template #timeslot *ngIf="course?.timeslots" class="timeslots s-padding-l">{{ course?.timeslots }}</ng-template>
</div>

在您需要的组件中:

Array = Array;

【讨论】:

    【解决方案2】:

    你只能借助组件方法来实现。

    <ng-container *ngIf="course?.timeslots && checkType(course.timeslots);else timeslot">
       <div *ngFor="let courseTimeslot of course.timeslots" class="timeslots s-padding-l">{{ courseTimeslot.timeslot }}
       </div>
    </ng-container>
    
    <ng-template #timeslot *ngIf="course?.timeslots" class="timeslots s-padding-l">{{ course?.timeslots }}</ng-template>
    

    组件:

    checkType(dataItem){
       return typeof dataItem === "object" && dataItem.length > 0;
     }
    

    【讨论】:

      猜你喜欢
      • 2022-01-27
      • 1970-01-01
      • 2015-01-02
      • 1970-01-01
      • 2021-09-21
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多