Angular 角度计数数组中的项目总数,但不会减慢速度
目前我正在检查Angular 角度计数数组中的项目总数,但不会减慢速度,angular,typescript,angular-ui-router,Angular,Typescript,Angular Ui Router,目前我正在检查检查设备(obj),查看是否存在值。。。我还需要的是,分开计算。设备在数组中出现多少次 组件。ts public checkDevice(obj) { if (obj == null || obj == '' || obj == '-1') { return false; } else { return true; } } component.html <div class="float-left" *ngIf="ch
检查设备(obj)
,查看是否存在值。。。我还需要的是,分开计算。设备在数组中出现多少次
组件。ts
public checkDevice(obj) {
if (obj == null || obj == '' || obj == '-1') {
return false;
} else {
return true;
}
}
component.html
<div class="float-left" *ngIf="checkDevice(obj.device_token) == true">
<i class="fa fa-icon" aria-hidden="true"></i>
</div>
我想你也可以写这段代码
<div class="float-left" *ngIf="obj.device_toke">
<i class="fa fa-icon" aria-hidden="true"></i>
</div>
我建议您不要在HTML中使用函数来绑定数据,这可能会有性能问题,因为每次都会调用函数来检查
我认为您的设备已经有了阵列,并且您正在一个ngFor中迭代
我建议您采取以下步骤:
- 创建一个purgued数组,在该数组中清除所有带有标记en null或empty的设备
- 使用该数组将其绑定到您的ngFor(您将确保已加载令牌)
这样做可以解决两件事:
- 将函数绑定到*ngIf的性能问题
- 您将解决计数问题,因为您将有一个包含所有具有令牌的项的新数组
如果您只想测试对象属性是否存在,那么应该执行以下操作:
<div class="float-left" *ngIf="obj.device_token">
<i class="fa fa-icon" aria-hidden="true"></i>
</div>
如果要获取数组中设备对象的引用,请尝试以下解决方案:
getDeviceOccurrence(deviceArray: Array<object>, device: object): number {
return deviceArray.reduce((accumulator: number, currentValue: object) => {
if (_.isEqual(currentValue, device)) {
return accumulator = accumulator + 1;
}
return accumulator;
}, 0);
}
getDeviceOccurrence(deviceArray:Array,device:object):编号{
return deviceArray.reduce((累加器:number,currentValue:object)=>{
if(u.isEqual(当前值,设备)){
返回蓄能器=蓄能器+1;
}
回流蓄能器;
}, 0);
}
建议解决方案的注意事项:
<span>{{ getDeviceOccurrence(devices, device) }}</span>
- 对于比较对象,更容易导入和使用其功能
- 该函数采用两个参数。第一个是容纳设备的阵列。第二个是设备。函数将返回一个数字,该数字是数组中设备对象的出现次数
- 此解决方案使用
模板中的用法:
<span>{{ getDeviceOccurrence(devices, device) }}</span>
{{getDeviceOccurrence(设备,设备)}
你的obj长什么样?您想在哪里显示设备计数?您不应该在模板中数据绑定函数。您指的是哪个Array
?@Ntwobike我希望设备计数正好在图标标记之后。@lealcelderio我更新并发布了ArrayI应该能够像这样调用{accumulator}
在component.html中?