javascript - איך להאזין ל-sortChange(event) ב-Angular עבור ag-Grid?
יש לי כאן דוגמה מאוד בסיסית: https://stackblitz.com/edit/angular-ag-grid-angular-cwvpic?file=app/my-grid-application/my-grid-application.component.ts
ב-ag-grid הזה אני רוצה להדפיס איזו עמודה נלחצה ובאיזה אופן היא מסודרת. כדי לעשות זאת מצאתי את השיטה sortChange(event) במסמכים הרשמיים. אבל לא הצלחתי למצוא דרך ליישם את השיטה הזו. הנה מה שניסיתי.
sortChange(event){
console.log(event);
}
<div style="width: 200px;">
<ag-grid-angular
(sortChange)="sortChange($event)"
#agGrid style="width: 100%; height: 200px;"
class="ag-theme-fresh" [gridOptions]="gridOptions">
</ag-grid-angular>
</div>
לצערי זה לא עבד. זה לא מדפיס כלום. אתה יודע איך אני יכול להקשיב לשינויים במיון בכל עמודה לפי שם העמודה?
תשובה #1
זה sortChanged ולא sortChange (יש d).
נסה :
printSortStateToConsole() {
const sortState = this.gridApi.getSortModel();
if (sortState.length == 0) {
console.log("No sort active");
} else {
console.log("State of sorting is:");
for (var i = 0; i < sortState.length; i++) {
const item = sortState[i];
console.log(i + " = {colId: " + item.colId + ", sort: " + item.sort + "}");
}
}
}
onGridReady(params: any) {
this.gridApi = params.api;
}
<div style="width: 200px;">
<ag-grid-angular
#agGrid style="width: 100%; height: 200px;"
class="ag-theme-fresh"
(sortChanged)="printSortStateToConsole($event)"
(gridReady)="onGridReady($event)"
[gridOptions]="gridOptions">
</ag-grid-angular>
</div>
עריכה: הקוד שלך טוב, אבל אתה צריך לאכלס את this.gridApi כאשר הרשת מוכנה כך (בדוק (gridReady) ו-onGridReady). אני מבין מה אתה רוצה שיופיע בקונסולה בצורה הזו.
תשובה #2
HTML :
<ag-grid-angular>
...
(sortChanged)="onSortChanged($event)">
</ag-grid-angular>
TS :
onSortChanged(event) {
const sortedColumn = event.columnApi.getColumnState().find(col => Boolean(col.sort));
console.log(sortedColumn, '>> col sort state <<');
// here you can do the logic for the sorted column and direction
דוגמת לוג קונסול:
{
"colId": "created_at",
"width": 233,
"hide": false,
"pinned": null,
"sort": "asc",
"sortIndex": 0,
"aggFunc": null,
"rowGroup": false,
"rowGroupIndex": null,
"pivot": false,
"pivotIndex": null,
"flex": null
}
