angular - Angular 7 Keypair 表达式顺序
问题描述
我正在尝试使用 Angular 7 构建一个表,该表具有一个表作为父组件,每行的子组件除外,第一行除外。我将一个键值管道值传入每一行,在显示子组件之前,我还首先循环遍历父组件中的键值对(见图)。我正在使用ngFor
循环键值对,但我正在与它在子组件中显示的顺序作斗争。我知道默认情况下,键值是根据键按字母顺序返回的。我能够null
在父组件上设置使用ngFor
它的表达式并且它工作正常,但是当我尝试对表达式使用 null 时,我在子组件中得到一个错误。这是我得到的:
table.component.ts
这是在导出类中。
intervals: {[key: string]: string} = {
'past-hour': 'Past Hour',
'today': 'Today',
'yesterday': 'Yesterday'
};
// This is the one that I'm having trouble with.
responseStatus: {[key: string]: string} = {
'success': 'Success',
'error': 'Error %',
'throttle': 'Throttle %'
};
table.component.html
<table class="compare-table text-right">
<tbody>
<tr>
<td></td>
<!-- The null works here -->
<td *ngFor="let status of responseStatus | keyvalue: null">
{{ status.value }}
</td>
</tr>
<tr
table-row
*ngFor="let interval of intervals | keyvalue: null"
[interval]="interval"
[responseStatuses]="responseStatus">
</tr>
</tbody>
</table>
表行组件.ts
export class TableRowComponent implements OnInit {
@Input() interval;
@Input() responseStatuses: {[key: string]: string};
constructor() { }
ngOnInit() {
}
}
table-row.component.html 前端出现此错误(编译良好)。如果我删除空值,它会按字母顺序显示。因此,它不像第一行那样显示成功、错误和油门,而是显示错误、成功、油门。
<td>
{{ interval.value}}
</td>
<td *ngFor="let response of responseStatuses | keyvalue: null">
{{ response.value }}
</td>
我感谢任何人的任何反馈。我对此非常陌生,想知道我做错了什么。:) 谢谢!
更新 事实证明,控制台也不喜欢父组件上的 null ,但它起作用了……我要做的就是按设置的顺序显示键值对,而不是按字母顺序。这是一个堆栈闪电战。
解决方案
根据这里的文档:https ://angular.io/api/common/KeyValuePipe
输出数组将按键排序。默认情况下,比较器将使用 Unicode 点值。如果您的键是复杂类型,您可以选择传递 compareFn。
所以订购是设计使然。正如它所说,你可以提供一个比较功能,但我不明白这会有什么帮助。不会有“书面”顺序(据我所知)。
管道相对较新......所以这里的keyvalue
一个选择是按照我们在管道之前的方式来做keyvalue
,那就是在代码中处理它。
在组件中:
get keys() : Array<string> {
console.log(this.responseStatus);
return Object.keys(this.responseStatus);
}
此代码仅按定义的顺序返回一组键。
在 html 中:
<div *ngFor="let key of keys">
{{ responseStatus[key] }}
</div>
此代码循环遍历这些键并从键值对访问元素。
更新堆栈闪电战: https ://stackblitz.com/edit/angular-xucsn6
推荐阅读
- machine-learning - 如何使用机器学习对个性化阈值问题进行建模
- excel - Cells.Formula 不适用于空字符串
- sql - SQL sum 按字段分组,所有行
- javascript - 如何突出显示文本使用 type.js 文本
- android-studio - 安卓梯度同步
- java - 使用fabric8 maven插件替换kubernetes statefulsets失败
- c++ - 字典上最小的字符串旋转
- powershell - 使用 PowerShell 解析 IBM MQ 报告以格式化 Prometheus 可以使用
- emacs - 如何忽略 Jekyll 中的 emacs 临时文件?
- android - 在 EditText Android 中强制使用尾随零