简体   繁体   English

如何使用 *ngIf 检查 Angular 2 模板中的空对象

[英]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

Plunker examplePlunker 示例

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) != '{}'仅适用于{}空情况,不适用于nullundefined情况
  • Object.getOwnPropertyNames(previous_info).length also did not work, as Object is not accessible in the template Object.getOwnPropertyNames(previous_info).length也不起作用,因为在模板中无法访问Object
  • I would not like to create a dedicated variable 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 = nullprevious_info = undefinedprevious_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.

相关问题 ngIf 检查对象是否为空 [完成] - ngIf check if object is empty [done] 如何在ngIF条件下检查object是null还是在angular中未定义 - how to check if object is null or undefined in angular in ngIF condition 如何检查 ReportControl object 上是否存在 Reportid 或不使用 *ngif? - How to check Reportid exist on ReportControl object or not using *ngif? 如何在 Angular2 的 ngIf 中检查变量类型 - How to check type of variable in ngIf in Angular2 如何在AngIf 6中使用Jasmine从ngIf router.url检查元素是否可见 - How do I check if element is visible or not from an ngIf router.url check using Jasmine in Angular 6 使用* ngIf,Angular 2中的插值访问本地模板变量 - Access local template variable using interpolation inside *ngIf, Angular 2 如何检查流星模板中的空对象? - How Do I Check For an Empty Object in a Meteor Template? 如何执行注销触发器并执行ngIf身份验证检查-Angular 4和Ionic 3 - how to execute logout trigger and do ngIf authentication check - Angular 4 and Ionic 3 如何使用 lodash _isEmpty 检查对象是否为空? - How to check if object is empty using lodash _isEmpty? 在Angular App中对网络请求之前的空对象使用条件检查 - Using Conditional Check on Empty Object Before Network Request in Angular App
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM