Skip ngFor if array is empty

i want to skip ngFor if the retrieved data length is empty
i tried to use ngIf also but didn’t work

      <ion-slides autoplay="3000" *ngIf="Ads.length" class="slideroption" loop="true" speed="300">
        <ion-slide *ngFor="let Ad of Ads">
          <img [src]="Ad?.image">
        </ion-slide>
      </ion-slides>

any help please …

*ngFor will do nothing if your array is empty, I don’t see your problem…

1 Like

try this
*ngIf=“Ads.length != 0”

didn’t work …54%20PM

IF you’re doing TS you can also use a ? on the *ngIf for the element and it will optionally check for an instance of Ads (true false i believe) or go by length if array. Should work for ya.

<ion-slides autoplay=“3000” *ngIf=“Ads?.length > 0” class=“slideroption” loop=“true” speed=“300”>
<ion-slide *ngFor=“let Ad of Ads”>
<img [src]=“Ad?.image”>

The error message tells you exactly what is wrong, and if you had proper types on all of your object properties, you would have been warned at compile time that you are trying to assign a string “no records” to what is supposed to be an array.

1 Like

you right … but how to skip the ngFor if there no records ?
sorry i’m new in angular

As @kocei already said, there is no need to concern yourself with that.

Here is how:

  1. you share you code you have so far including ts file to show what “Ads” is etc
  2. couple with your template this creates context for community here to help you out
    3.you get your answer;)

So start with sharing full code!

its retrieved array from api

  Ads: any[];
      Http.get(this.apiURl)
      .map(res => res.json())
      .subscribe(data => {
        this.Ads = data;
      });

Everything about this is horrible.

  • You are abusing any
  • You are declaring object properties with initial upper case, which should be reserved for classes
  • You are declaring an array property without an initializer
  • You are needlessly calling json()
  • You are subscribing in the same place you create an Observable
3 Likes

Well its hard to navigate your code but try initializing your array in constructor as empty array:

Ads = ;

So that before it gets its data from your api it is a valid array (even though empty)

There is a generic tag in Angular called ng-container you can wrap logic in to prevent all tags inside it from rendering.

<ng-container *ngIf="Ads.length">
<ion-slides autoplay="3000" class="slideroption" loop="true" speed="300">
        <ion-slide *ngFor="let Ad of Ads">
          <img [src]="Ad?.image">
        </ion-slide>
      </ion-slides>
</ng-container>
2 Likes

thank you Dan for reply … worked

No problem.

You have to remember that Ionic 3 is really just a UI framework. At it’s core an Ionic 3 app is Angular 4 code, and you can use any standard Angular syntax. So it might be good to learn Angular outside of Ionic as well, just so you have a better grasp of Angual as a whole and not just the Ionic subset.

1 Like

thanks very much for your advice