作者:廖哲皓(Howard Liao)|Frontend Lead(Principal Engineer)
我是廖哲皓,從事前端開發 14 年以上。企業後台最常見的畫面就是「資料表格」:要分頁、要排序、要篩選,資料量大時還要交給後端處理。
這篇用我的範例專案,示範 Angular 21 搭配 Kendo UI Grid 的寫法。程式碼:https://github.com/necpoctt/angular-kendo-ui-demo
線上展示:https://angular-kendo-ui-demo.vercel.app/
新版 Angular 不再需要 NgModule,每個頁面都是 standalone 元件,路由用 loadComponent 延遲載入:
{
path: 'manage',
loadComponent: () =>
import('./manage/employee.component')
.then((m) => m.EmployeeComponent),
title: '員工薪資管理系統',
}
app.config.ts 裡要記得加上 provideAnimations(),Kendo 的元件需要動畫支援。
Kendo Grid 把表格的狀態都放在一個 State 物件裡:
public state: State = {
skip: 0,
take: 10,
sort: [],
filter: { logic: 'and', filters: [] },
};
使用者換頁、排序或篩選時,Grid 會觸發 dataStateChange 事件,並把新的 State 傳出來。我們只要把它存起來,再拿去查資料:
public dataStateChange(state: State): void {
this.state = state;
this.loadItems();
}
這個設計的好處是:分頁、排序、篩選都走同一條路。不用為每個功能各寫一個事件處理函式。
範例裡用 @progress/kendo-data-query 的 process() 在前端模擬後端,並加上 300ms 延遲,讓 loading 效果出來:
getEmployees(state: State): Observable<GridDataResult> {
const result = process(MOCK_DATA, state);
return of(result).pipe(delay(300));
}
正式專案只要把這段換成 HTTP 請求,把 State 轉成 API 參數送給後端。元件完全不用改。
除了使用者自己篩選,也可以用按鈕一鍵套用條件,例如「只看 10 萬以上」:
this.state.filter = {
logic: 'and',
filters: [{ field: 'salary', operator: 'gte', value: 100000 }],
};
this.state.skip = 0;
this.loadItems();
記得把 skip 歸零。不然使用者原本在第 3 頁,套用篩選後可能看到空白頁。
用 kendoGridCellTemplate 可以自訂每一格的內容,例如姓名前面加上頭像縮寫、金額超過門檻時顯示紅色。中文介面的篩選文字,則可以用 kendo-grid-messages 改成「在職中」、「已離職」這類用語。
企業後台的重點不是畫面多漂亮,而是資料流程清楚、好維護。把表格狀態集中在一個物件裡,就是一個很好的開始。
關於我:廖哲皓(Howard Liao),台北 Frontend Lead(Principal Engineer),專長 React、Vue、Angular、TypeScript、Node.js。
個人網站:https://necpoctt.github.io/
GitHub:https://github.com/necpoctt
LinkedIn:https://www.linkedin.com/in/howard-liao-a2325aab/
本文同步發表於 Medium:https://medium.com/@necpoctt/fa0ca4dda37d