使用ngIf检查数组长度或显示div的内容 [英] using ngIf to check array length or content to display div

查看:441
本文介绍了使用ngIf检查数组长度或显示div的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据数据数组的长度来控制是否显示div.如果有数据,请继续显示div,如果没有,则将其隐藏.我正在使用* ngIf,但我想问两种不同的方法,一种方法是否比另一种方法好,也许是为什么.

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

*ngIf="dataArray?.length > 0"

推荐答案

要回答您的问题,可以使用第二种方法来完成要实现的功能:

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

*ngIf="dataArray?.length > 0"

因为这实际上是在测试数组是否存在并且其长度是否大于零(如Sajeetharan在他的回答中提到的那样).

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"

*ngIf="!!dataArray?.length"

第一种选择是使用数组长度不能小于0且0为 falsy 和> 0为 truthy 的事实.第二种选择是将真/假状态显式转换为真或假.

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.

我更喜欢这样写:

*ngIf="dataArray?.length"

在编写JS时,我倾向于编写简洁的代码,并最终在可读性和紧凑性之间做出权衡.这主要是因为JS是解释性语言,简洁的代码为您提供了更高的效率.

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.

移动到组件:这是Angular的起点.我要说的是,这实际上取决于权衡取舍,没有是"-否"的答案.对于我们当前正在使用的大型Angular4应用程序,我们不会对其进行移动.但是,如果还有其他条件或涉及更多逻辑,我们将其移动并设置一个标志.因此,要回答您的问题,如果您真的想进一步优化它,则可以使用标志代替,并在将元素添加到数组的位置将其设置为true.

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.

这篇关于使用ngIf检查数组长度或显示div的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆