angular - 使用指令对 *ngFor 中使用的对象数组进行排序
问题描述
使用 Angular,我创建了一个带有排序指令的表,该指令根据单击的标题对表进行排序。但是,如果输入数据有任何空值,排序指令将无法正常工作。
这是我在指令中的排序功能:
sortArray (): Array<any> {
let tempArray: Array<any> = this.data;
tempArray.sort((a, b) => {
let aKey = a[this.key];
let str1: string = a[this.key].toLowerCase();
let str2: string = b[this.key].toLowerCase();
if (this.toggleSort) {
if (str1 < str2) {
return -1;
}
if (str1 > str2) {
return 1;
}
}
else {
if (str1 > str2) {
return -1;
}
if (str1 < str2) {
return 1;
}
}
return 0;
});
return tempArray;
}
我怎样才能让它对空值起作用?
解决方案
sortArray (): Array<any> {
let tempArray: Array<any> = this.data;
tempArray.sort((a, b) => {
let aKey = a[this.key];
let str1: string = a[this.key].toLowerCase();
let str2: string = b[this.key].toLowerCase();
if (this.toggleSort) {
if (!str1 && !str2) {
return 0;
} else if (!str1) {
return 1;
} else if (!str2) {
return -1;
}
//rest of your logic if neither is null
if (str1 < str2) {
return -1;
}
if (str1 > str2) {
return 1;
}
}
else {
if (str1 > str2) {
return -1;
}
if (str1 < str2) {
return 1;
}
}
return 0;
});
return tempArray;
}
推荐阅读
- rpm - 在 CentOS 8 的本地存储库中安装 httpd
- mysql - 错误 1045 (28000):在终端上使用以下命令拒绝用户 'root'@'localhost'(使用密码:NO)的访问:sudo mysql、和、、mysql
- c++ - 展平到一维的优势
- graphql - Graphql 类型解析器(按 id)
- javascript - 函数正常执行但 addeventlistener 不会执行函数
- database - Spark 避免每次执行整个查询
- python - 与在 vscode 中使用 Go to Definition 和 Peek Definition 命令相关
- amazon-web-services - Terraform 错误:运行 terraform 计划时条件类型不正确
- java - 在对 JAX-RS 控制器的 PUT 请求中将 LocalDateTime 设置为 Null
- pandas - 如何使用熊猫保持真值和无值?