首页 > 解决方案 > 角度检查 json 有孩子或为空

问题描述

要检查子和子变量或为空

{{ CustomJsonSchema?.properties | json }} // if empty returns {}
{{ CustomJsonSchema?.properties | json }} // if not empty returns { "street_1": { "type": "string" }, "zip_code": { "type": "string" }, "first_name": { "type": "string" } }

HTML:

<div>Has Elements</div>
<div>Empty</div>

标签: jsonangular

解决方案


编辑

虽然这种方法可行,但它会isEmpty在每次更改检测时不必要地触发该功能,即使对象没有更改也是如此。要获得更有效的方法,请遵循@Chellapan 的方法。


您可以在组件中创建一个函数来检查您的对象是否为空并在模板中使用它。

isEmpty(obj) {
    return Object.keys(obj).length === 0 && obj.constructor === Object;
}

根据 ECMAScript 版本或您是否使用第三方库(如lodashor underscore),您可以查看此答案以了解检查对象是否为空的不同方法。

然后在你的模板中

<div *ngIf="CustomJsonSchema?.properties && isEmpty(CustomJsonSchema.properties)">
    Empty
</div>
<div *ngIf="CustomJsonSchema?.properties && !isEmpty(CustomJsonSchema.properties)">
    Has elements
</div>

第一个条件是在检查它是否为空之前确保CustomJsonSchema.properties存在。


推荐阅读