Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using ngIf to check array length or content to display div

Tags:

angular

I would like to control whether to display my div or not depending on the length of the data array. if there is data go ahead and show the div and if not then just hide it. I am using *ngIf but i wanted to ask about two different ways and if one is better than the other and maybe why.

*ngIf="dataArray?"

or

*ngIf="dataArray?.length > 0"
like image 966
bluePearl Avatar asked Sep 11 '25 00:09

bluePearl


1 Answers

To answer your question, the functionality that you want to achieve can be done by using second way:

*ngIf="dataArray?.length > 0"

since this is really testing if array exists and its length is more than zero (as mentioned by Sajeetharan in his answer).

It also be written in following two different ways to achieve the same result:

*ngIf="dataArray?.length"

or

*ngIf="!!dataArray?.length"

The first alternative, uses the fact that array length cannot be less than 0 and 0 is falsy and >0 is truthy. The second alternative explicitly converts the truthy/falsy states to true or false.

I will prefer to write it this way:

*ngIf="dataArray?.length"

While writing JS, I tend to write code that is concise and end up doing a trade-off between readability and compactness. This is primarily because JS is interpreted language and concise code give you more efficiency.

I agree there are minifiers available which do that for us, but there are some cases where they may not work like template expressions.

Moving to component: That is where Angular starts. I'd say this really depends on the trade-offs and there is no YES-No answer. For our current large Angular4 application that I am working on, we are not moving these. But if there are some additional conditions or involve even slightly more logic, we move it component and set up a flag. So, to answer your question, if you really want to optimize this further, then you can use a flag instead and in the place where elements are added to array, set it to true.

That's how I understand it. If anyone has more to add or correct, please write in comments.

like image 162
Abhi Avatar answered Sep 13 '25 13:09

Abhi