[英]How to check empty object in angular 2 template using *ngIf
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?但是我的代码是错误的,最好的方法是什么?
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
.每个
{}
创建一个新实例,并且====
不同对象实例的比较总是导致false
。 When they are convert to strings ===
results to true
当它们转换为字符串时
===
结果为true
From the above answeres, following did not work or less preferable:根据上述答案,以下内容不起作用或不太可取:
(previous_info | json) != '{}'
works only for {}
empty case, not for null
or undefined
case (previous_info | json) != '{}'
仅适用于{}
空情况,不适用于null
或undefined
情况Object.getOwnPropertyNames(previous_info).length
also did not work, as Object
is not accessible in the template Object.getOwnPropertyNames(previous_info).length
也不起作用,因为在模板中无法访问Object
this.objectLength = Object.keys(this.previous_info).length !=0;
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)); }
Solution: keyvalue pipe 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
或previous_info = undefined
或previous_info = {}
并视为假值时,它运行良好。
<div *ngIf="(previous_info | keyvalue)?.length">
keyvalue - Transforms Object or Map into an array of key value pairs.
keyvalue - 将 Object 或 Map 转换为键值对数组。
?.
?. - The Angular safe navigation operator (?.) is a fluent and convenient way to guard against null and undefined
- Angular 安全导航运算符 (?.) 是一种防止 null 和 undefined 的流畅且方便的方法
DEMO: demo with angular 9, though it works for previous versions as well演示: 使用 angular 9 进行演示,尽管它也适用于以前的版本
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));
}
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可能重复的问题Angular2 - 如果不检查 {{object.field}} 是否存在则错误
This worked for me:这对我有用:
Check the length
property and use ?
检查
length
属性并使用?
to avoid undefined
errors.以避免
undefined
的错误。
So your example would be:所以你的例子是:
<div class="comeBack_up" *ngIf="previous_info?.length">
UPDATE更新
The length property only exists on arrays. length 属性仅存在于数组中。 Since the question was about objects, use
Object.getOwnPropertyNames(obj)
to get an array of properties from the object.由于问题是关于对象的,因此请使用
Object.getOwnPropertyNames(obj)
从对象中获取一组属性。 The example becomes:示例变为:
<div class="comeBack_up" *ngIf="previous_info && Object.getOwnPropertyNames(previous_info).length > 0">
The previous_info &&
is added to check if the object exists.添加
previous_info &&
以检查对象是否存在。 If it evaluates to true
the next statement checks if the object has at least on proporty.如果它评估为
true
,则下一条语句检查对象是否至少具有比例。 It does not check whether the property has a value.它不检查属性是否具有值。
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"
Just for readability created library ngx-if-empty-or-has-items it will check if an object, set, map or array is not empty.只是为了可读性,创建库ngx-if-empty-or-has-items它将检查对象、集合、映射或数组是否不为空。 Maybe it will help somebody.
也许它会帮助某人。 It has the same functionality as ngIf (then, else and 'as' syntax is supported).
它具有与 ngIf 相同的功能(然后,支持 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.