使用我們希望能夠排序以在組件中顯示的數(shù)據(jù)數(shù)組,并且它似乎沒有排序或更新 DOM,但是我有一個(gè)正確演示該概念的工作代碼示例,它應(yīng)該正在排序,但在 angular 應(yīng)用程序中,它根本沒有被排序。存儲(chǔ)原始數(shù)據(jù)的父組件將數(shù)據(jù)存儲(chǔ)在名為 的輸入?yún)?shù)對(duì)象上Batch,我們正在排序的數(shù)組位于 上Batch.Invoices.Results。來自子組件的事件沒問題,確認(rèn)合適的數(shù)據(jù)冒泡到父組件。應(yīng)該對(duì)數(shù)組進(jìn)行排序的函數(shù)如下所示: 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)); }所有控制臺(tái)日志都用于調(diào)試器可見性,輸出如下:在我的測試文件(非角度)中的哪個(gè)位置看起來像這樣:(哪里data是來自 Angular 應(yīng)用程序的數(shù)組的直接副本。const ascendingData = [...data];const descendingData = [...data];const sortedDescending = descendingData.sort((a, b) => a['VendorName'] < b['VendorName']? 0 : 1)const sortedAscending = ascendingData.sort((a, b) => a['VendorName'] > b['VendorName']? 0 : 1);const vendorListAscending = sortedAscending.map(x => x.VendorName);const vendorListDescending = sortedDescending.map(x => x.VendorName);console.log(vendorListDescending);console.log(vendorListAscending);輸出如下所示:所以我看到排序應(yīng)該起作用,但它在 Angular 中沒有發(fā)生。如何對(duì)數(shù)組進(jìn)行排序,并同時(shí)更新 DOM?
基于排序數(shù)組更新組件。角 (4.3)
慕田峪9158850
2021-08-20 17:59:38