Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

*ngIf check is array empty then show message [closed]

I used the following code to check if array is empty then show message else show the list. But it only shows list is working. "No messages" is not displaying. What's wrong here?

<ion-row *ngFor="let item of globalArray">
    <div *ngIf="!globalArray?.length > 0">
        <p>No messages</p>
    </div>
    <div *ngIf="globalArray?.length > 0">
        <ion-item>
            {{item.message}}
        </ion-item>
    </div>
</ion-row>
like image 768
GunarathneMDD Avatar asked Mar 08 '18 04:03

GunarathneMDD


People also ask

How do I know if my Ngfor is empty?

You can simply have an *ngIf condition after the loop. Array. prototype. filter can be used to check if there are any items with isSelected .

Is array in angular?

isArray() Function in AngularJS is used to return TRUE if the reference is an array and FALSE if it is not an array. Syntax: angular. isArray(value);


1 Answers

because in your array

<ion-row *ngFor="let item of globalArray">
    <div *ngIf="!globalArray?.length > 0">
        <p>No messages</p>
    </div>
    <div *ngIf="globalArray?.length > 0">
        <ion-item>
            {{item.message}}
        </ion-item>
    </div>
</ion-row>

you are directly iterating and checking the length of an array inside ngFor, which will never execute. you need to check the length outside ngFor or before iterating the array. you can check this from ts file too, or you can handle this in your view.

In your view you can handle like:

<div *ngIf="!globalArray || globalArray.length === 0">
        <p>No messages</p>
    </div>
<div *ngIf="globalArray || globalArray.length > 0">
<ion-row *ngFor="let item of globalArray">
        <ion-item>
            {{item.message}}
        </ion-item>
    </ion-row>
</div>

In the .ts file you can similarly check the array length and make a variable toggle on basis of this and use ngIf with that variable on both the Div.

like image 109
Hrishikesh Kale Avatar answered Sep 28 '22 02:09

Hrishikesh Kale