Javascript 如何使用 *ngIf 检查 angular 2 模板中的空对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37111005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check empty object in angular 2 template using *ngIf
提问by Günter Z?chbauer
I want to check if my object is empty dont render my element, and this is my code:
我想检查我的对象是否为空不要渲染我的元素,这是我的代码:
<div class="comeBack_up" *ngIf="previous_info != {}">
<a
[routerLink]="['Inside_group_page',{'name':previous_info.path | dotTodash }]"
>
{{previous_info.title}}
</a>
</div>
but my code is wrong, what is the best way to do this?
但我的代码是错误的,最好的方法是什么?
回答by Günter Z?chbauer
This should do what you want:
这应该做你想做的:
<div class="comeBack_up" *ngIf="(previous_info | json) != ({} | json)">
or shorter
或更短
<div class="comeBack_up" *ngIf="(previous_info | json) != '{}'">
Each {}
creates a new instance and ====
comparison of different objects instances always results in false
. When they are convert to strings ===
results to true
每个都会{}
创建一个新实例,并且====
不同对象实例的比较总是导致false
. 当它们转换为字符串时,===
结果为true
回答by Thierry Templier
You could also use something like that:
你也可以使用类似的东西:
<div class="comeBack_up" *ngIf="isEmptyObject(previous_info)" >
with the isEmptyObject
method defined in your component:
使用isEmptyObject
组件中定义的方法:
isEmptyObject(obj) {
return (obj && (Object.keys(obj).length === 0));
}
回答by Sumit
From the above answeres, following did not work or less preferable:
从上述答案中,以下不起作用或不太可取:
(previous_info | json) != '{}'
works only for{}
empty case, not fornull
orundefined
caseObject.getOwnPropertyNames(previous_info).length
also did not work, asObject
is not accessible in the template- I would not like to create a dedicated variable
this.objectLength = Object.keys(this.previous_info).length !=0;
I would not like to create a dedicated function
isEmptyObject(obj) { return (obj && (Object.keys(obj).length === 0)); }
(previous_info | json) != '{}'
仅适用于{}
空箱,不适用于null
或undefined
箱Object.getOwnPropertyNames(previous_info).length
也不起作用,因为Object
在模板中无法访问- 我不想创建专用变量
this.objectLength = Object.keys(this.previous_info).length !=0;
我不想创建专用功能
isEmptyObject(obj) { return (obj && (Object.keys(obj).length === 0)); }
Solution:keyvaluepipe along with ?.(safe navigation operator); and it seems simple.
解决方案:键值管道和?。(安全导航操作员);而且看起来很简单。
It works well when previous_info = null
or previous_info = undefined
or previous_info = {}
and treats as falsy value.
当previous_info = null
orprevious_info = undefined
或previous_info = {}
and 视为假值时,它运行良好。
<div *ngIf="(previous_info | keyvalue)?.length">
keyvalue- Transforms Object or Map into an array of key value pairs.
?.- The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined
keyvalue- 将 Object 或 Map 转换为键值对数组。
?. - Angular 安全导航操作符 (?.) 是防止 null 和 undefined 的一种流畅便捷的方式
DEMO:demo with angular 9, though it works for previous versions as well
回答by Damiani
Above answers are okay. But I have found a really nice option to use following in the view:
上面的回答没问题。但我发现了一个非常好的选项,可以在视图中使用以下内容:
{{previous_info?.title}}
{{previous_info?.title}}
probably duplicated question Angular2 - error if don't check if {{object.field}} exists
回答by Loke
This worked for me:
这对我有用:
Check the length
property and use ?
to avoid undefined
errors.
检查length
属性并使用?
以避免undefined
错误。
So your example would be:
所以你的例子是:
<div class="comeBack_up" *ngIf="previous_info?.length">
UPDATE
更新
The length property only exists on arrays. Since the question was about objects, use Object.getOwnPropertyNames(obj)
to get an array of properties from the object. The example becomes:
length 属性只存在于数组中。由于问题与对象有关,因此请使用Object.getOwnPropertyNames(obj)
从对象中获取属性数组。示例变为:
<div class="comeBack_up" *ngIf="previous_info && Object.getOwnPropertyNames(previous_info).length > 0">
The previous_info &&
is added to check if the object exists. If it evaluates to true
the next statement checks if the object has at least on proporty. It does not check whether the property has a value.
将previous_info &&
被添加到检查对象存在。如果它评估为true
下一条语句,则检查该对象是否至少按比例进行。它不检查属性是否具有值。
回答by alexKhymenko
Just for readability created library ngx-if-empty-or-has-itemsit will check if an object, set, map or array is not empty. Maybe it will help somebody. It has the same functionality as ngIf (then, else and 'as' syntax is supported).
只是为了可读性创建的库ngx-if-empty-or-has-items它将检查对象、集合、映射或数组是否不为空。也许它会帮助某人。它具有与 ngIf 相同的功能(支持 then、else 和 'as' 语法)。
arrayOrObjWithData = ['1'] || {id: 1}
<h1 *ngxIfNotEmpty="arrayOrObjWithData">
You will see it
</h1>
or
// store the result of async pipe in variable
<h1 *ngxIfNotEmpty="arrayOrObjWithData$ | async as obj">
{{obj.id}}
</h1>
or
noData = [] || {}
<h1 *ngxIfHasItems="noData">
You will NOT see it
</h1>
回答by Mukul_Vashistha
A bit of a lengthier way (if interested in it):
有点长的方式(如果有兴趣的话):
In your typescript code do this:
在您的打字稿代码中执行以下操作:
this.objectLength = Object.keys(this.previous_info).length != 0;
And in the template:
在模板中:
ngIf="objectLength != 0"