1

I have two different responses, one there we need to loop over the object to show the right response. And the other one we just show the variable.

What I have tried is an ng-if else but it is not working.

it is about this piece of code:

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

Is this the right way to do otherwise I would like to hear any other options.

Sireini
  • 4,142
  • 12
  • 52
  • 91
  • `ng-if else` only 1 condition can be true, so if you want to do both you don't need ng-if. Just use `ng-container` instead of `ng-template` and remove the `else timeslot` – penleychan Dec 19 '18 at 15:01
  • @penleychan it is not both because on one page I need to show the if and on an other page the else statement – Sireini Dec 19 '18 at 15:03
  • As of now the way your code works is if `courseTImeslot` is `null` it will display your template `timeslot`. I am confused what you mean by 2 separate pages? Is the code above not contained in the same component? – penleychan Dec 19 '18 at 15:07
  • https://stackoverflow.com/questions/43726749/pass-variable-in-angular-2-template – Eliseo Dec 19 '18 at 15:11

2 Answers2

1

You can check if the object is an array or not

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

In your component you need:

Array = Array;
Aragorn
  • 5,021
  • 5
  • 26
  • 37
0

You can only achieve with help of component method.

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

Component:

checkType(dataItem){
   return typeof dataItem === "object" && dataItem.length > 0;
 }
Suresh Kumar Ariya
  • 9,516
  • 1
  • 18
  • 27