json - 角度检查 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>
解决方案
编辑
虽然这种方法可行,但它会isEmpty
在每次更改检测时不必要地触发该功能,即使对象没有更改也是如此。要获得更有效的方法,请遵循@Chellapan 的方法。
您可以在组件中创建一个函数来检查您的对象是否为空并在模板中使用它。
isEmpty(obj) {
return Object.keys(obj).length === 0 && obj.constructor === Object;
}
根据 ECMAScript 版本或您是否使用第三方库(如lodash
or underscore
),您可以查看此答案以了解检查对象是否为空的不同方法。
然后在你的模板中
<div *ngIf="CustomJsonSchema?.properties && isEmpty(CustomJsonSchema.properties)">
Empty
</div>
<div *ngIf="CustomJsonSchema?.properties && !isEmpty(CustomJsonSchema.properties)">
Has elements
</div>
第一个条件是在检查它是否为空之前确保CustomJsonSchema.properties
存在。
推荐阅读
- mysql - 使用 MySQL 在 SELECT 中附加通配符
- python - int() 和 int(input()) 的区别
- java - 如何使用 Gson 从 JSON 中一次读取一个变量?
- amazon-web-services - 如何确定一个 AWS s3 存储桶是否至少有一个公共对象?
- c++ - 如何在 PCL 中的体素过滤器后使用 SACS 分割
- python - 使用 openpyxl python 的大型数据集出错
- php - 潜在的mysql服务器问题?
- python - get( ) 接受 1 个位置参数,但给出了 3 个
- r - 如何在 R 中使用 ggplot 绘制甘特图时避免段之间的重叠
- django - 使用 IIS 服务器在 Windows 上运行 Django