我喜欢 ng-bootstrap 的人的工作,但我认为这绝对不是一个好例子。在我看来,让所有人都参与其中并不清楚。
我用材料角度在this SO 中制作了一些东西。一般来说,您需要一个具有两个功能的 API
getLength(string filter)
//and
getData(page:number,pageSize:number,filter:string,sortField:string,sortDirection:string)
在这个anohter stackbliz 是使用 ng-bootstrap 实现的
思路类似,我们定义了一些辅助变量
total: number;
filter = new FormControl();
page:number=1;
pageSize:number=5;
elements$:Observable<any>
pag:BehaviorSubject<any>=new BehaviorSubject<any>(null);
paginator$=this.pag.asObservable();
sort:any={active:"position",direction:'desc'};
isLoadingResults = true;
在 ngOnInit 中我们订阅了 filter.valueChanges
const obsFilter=this.filter.valueChanges.pipe(
debounceTime(200),
startWith(null),
switchMap((res: string) => this.dataService.getLength(res)),
tap((res: number) => {
this.page=1;
this.total = res;
})
);
this.elements$=merge(obsFilter, this.paginator$)
.pipe(
distinctUntilChanged(),
switchMap(res => {
return this.dataService.getData(
this.page,
this.pageSize,
this.filter.value,
this.sort.active,
this.sort.direction
);
}),
tap(_ => (this.isLoadingResults = false))
)
我们将使用辅助的 this.paginagtor$,它会在页面或 pageSize 发生变化以及排序发生变化时发出一个值,因此我们的函数 sort 变得像
onSort({column, direction}: SortEvent) {
// resetting other headers
this.sort={active:column,direction:direction}
this.headers.forEach(header => {
if (header.sortable !== column) {
header.direction = '';
}
});
this.pag.next(this.sort)
}
还有 .html(看看我们如何在分页器中拆分 [(ngModel)])
<form>
<div class="form-group form-inline">
Full text search: <input class="form-control ml-2" type="text" name="searchTerm" [formControl]="filter"/>
<span class="ml-3" *ngIf="isLoadingResults">Loading...</span>
</div>
<table class="table table-striped">
<thead>
<tr>
<th scope="col" sortable="position" (sort)="onSort($event)">No.</th>
<th scope="col" sortable="name" (sort)="onSort($event)">Name</th>
<th scope="col" sortable="weight" (sort)="onSort($event)">Weight</th>
<th scope="col" sortable="symbol" (sort)="onSort($event)">Symbol</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let element of elements$ | async">
<th scope="row">{{ element.position }}</th>
<td>
<ngb-highlight [result]="element.name" [term]="filter.value"></ngb-highlight>
</td>
<td><ngb-highlight [result]="element.weight | number" [term]="filter.value"></ngb-highlight></td>
<td><ngb-highlight [result]="element.symbol" [term]="filter.value"></ngb-highlight></td>
</tr>
</tbody>
</table>
<div class="d-flex justify-content-between p-2">
<ngb-pagination
[collectionSize]="total" [page]="page" (pageChange)="page=$event;pag.next($event)" [pageSize]="pageSize">
</ngb-pagination>
<select class="custom-select" style="width: auto" name="pageSize" [ngModel]="pageSize" (ngModelChange)="pageSize=$event;pag.next(-pageSize)">
<option [ngValue]="5">5 items per page</option>
<option [ngValue]="10">10 items per page</option>
<option [ngValue]="20">20 items per page</option>
</select>
</div>
</form>