Javascript 基于排序数组更新组件。角度(4.3)
使用我们希望能够排序以显示在组件中的数据数组,它似乎没有排序或更新DOM,但是我有一个工作代码示例,正确地演示了这个概念,它应该是排序的,但是在angular应用程序中,它根本没有得到排序 包含原始数据的父组件将数据存储在名为Javascript 基于排序数组更新组件。角度(4.3),javascript,arrays,angular,typescript,Javascript,Arrays,Angular,Typescript,使用我们希望能够排序以显示在组件中的数据数组,它似乎没有排序或更新DOM,但是我有一个工作代码示例,正确地演示了这个概念,它应该是排序的,但是在angular应用程序中,它根本没有得到排序 包含原始数据的父组件将数据存储在名为Batch的输入参数对象上,我们正在排序的数组位于Batch.Invoices.Results上。来自子组件的事件是正常的,并且确认适当的数据将冒泡到父组件 用于对数组进行排序的函数如下所示: public OnInvoiceSortChange({orderValue,
Batch
的输入参数对象上,我们正在排序的数组位于Batch.Invoices.Results
上。来自子组件的事件是正常的,并且确认适当的数据将冒泡到父组件
用于对数组进行排序的函数如下所示:
public OnInvoiceSortChange({orderValue, orderAscending}){
console.log(`Invoice Sorting has been called. Value: ${orderValue} . Ascending? ${orderAscending}`);
console.log(`Before:`);
console.log(this.BatchViewModel.Invoices.Results.map(x => x.VendorName));
const sortingArray = [...this.BatchViewModel.Invoices.Results];
if(orderAscending){
const sorted = sortingArray.sort((a, b) => a[orderValue] > b[orderValue] ? 1 : 0);
this.BatchViewModel.Invoices.Results = sorted;
console.log('Sorted');
console.log(sorted.map(x => x.VendorName));
} else {
const sorted = sortingArray.sort((a, b) => a[orderValue] < b[orderValue] ? 1 : 0);
this.BatchViewModel.Invoices.Results = sorted;
console.log(sorted.map(x => x.VendorName));
}
console.log(`After:`);
console.log(this.BatchViewModel.Invoices.Results.map(x => x.VendorName));
}
输出如下所示:
public OnInvoiceSortChange({orderValue, orderAscending}){
console.log(`Invoice Sorting has been called. Value: ${orderValue} . Ascending? ${orderAscending}`);
console.log(`Before:`);
console.log(this.BatchViewModel.Invoices.Results.map(x => x.VendorName));
const sortingArray = [...this.BatchViewModel.Invoices.Results];
if(orderAscending){
const sorted = sortingArray.sort((a, b) => a[orderValue] > b[orderValue] ? 1 : 0);
this.BatchViewModel.Invoices.Results = sorted;
console.log('Sorted');
console.log(sorted.map(x => x.VendorName));
} else {
const sorted = sortingArray.sort((a, b) => a[orderValue] < b[orderValue] ? 1 : 0);
this.BatchViewModel.Invoices.Results = sorted;
console.log(sorted.map(x => x.VendorName));
}
console.log(`After:`);
console.log(this.BatchViewModel.Invoices.Results.map(x => x.VendorName));
}
所以我认为排序应该是可行的,但它只是不发生在角度上。
如何对数组进行排序,并同时更新DOM?传递给
sort
的函数是错误的。它应该返回负值表示“更少”,正值表示“更大”,或零表示“相等”。如果orderValue
是数字,则最容易返回a[orderValue]-b[orderValue]
,如果不是,则只需将0
更改为-1
(顺便说一句,nameorderKey
可能会更清楚一些?)
我不认为angular与此有任何关系,但我现在不知道为什么会得到不同的结果。无论如何,您的排序函数无效(它声明a等于b,但同时b大于a),我希望修复此函数会有所帮助。是的,将其更改为您的建议,没有问题如果您使用角度材质显示数据,则必须刷新表。您可以使用扩展运算符(例如[…data])进行复制,或者使用
@ViewChild('table')myTable
并使用myTable.renderRows(),请参见,否则必须工作。我举了一个简单的例子