以下是一个使用Angular和Angular Material实现服务器端分页的示例代码:
npm install @angular/cli
ng new my-app
cd my-app
ng add @angular/material
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
MatTableModule,
MatPaginatorModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, PageEvent } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { HttpClient } from '@angular/common/http';
interface UserData {
id: number;
name: string;
email: string;
phone: string;
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
displayedColumns: string[] = ['id', 'name', 'email', 'phone'];
dataSource: MatTableDataSource;
pageSizeOptions: number[] = [5, 10, 25, 100];
totalRecords: number;
pageSize: number;
currentPage: number;
@ViewChild(MatPaginator) paginator: MatPaginator;
constructor(private http: HttpClient) { }
ngOnInit() {
this.pageSize = this.pageSizeOptions[0];
this.currentPage = 0;
this.loadData();
}
loadData() {
this.http.get('https://api.example.com/users', {
params: {
_start: (this.currentPage * this.pageSize).toString(),
_limit: this.pageSize.toString()
}
}).subscribe(data => {
this.totalRecords = data.total;
this.dataSource = new MatTableDataSource(data.data);
});
}
onPageChanged(event: PageEvent) {
this.currentPage = event.pageIndex;
this.pageSize = event.pageSize;
this.loadData();
}
}
ID
{{element.id}}
Name
{{element.name}}
Email
{{element.email}}
Phone
{{element.phone}}
这样,你就可以通过服务器端分页来显示和处理表格数据了。每当用户更改页码或每页的记录数时,会触发onPageChanged
方法来重新加载数据。