我正在使用Angular和ng-bootstrap做一个Web应用程序。我正在按照documentation from ng-bootstrap做一个带有过滤和分页的表格。我看到了解决方案,但是所有解决方案都包含Sort,并且代码更长,更复杂,就我而言,我不需要Sort。
目前,“过滤”功能运行良好,但分页功能却无法正常工作。至少,分页按钮的数量正在变化,但是它们不起作用。
模板:
<table class="table table-striped">
<thead class="thead-dark">
<tr>
<th scope="col">Localization</th>
<th scope="col">Position</th>
<th scope="col">Company</th>
<th scope="col">Created at</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let job of searchedJobs$ | async">
<td scope="row"><ngb-highlight [result]="job.location" [term]="filter.value"></ngb-highlight></td>
<td><ngb-highlight [result]="job.position" [term]="filter.value"></ngb-highlight></td>
<td><ngb-highlight [result]="job.company" [term]="filter.value"></ngb-highlight></td>
<td>{{job.createdAt.toDate() | date: 'mediumDate'}}</td>
</tr>
</tbody>
</table>
<div class="d-flex justify-content-between p-2">
<h6>{{jobs.length}} {{jobs.length > 1 ? 'jobs' : 'job'}} in this category</h6>
<ngb-pagination [collectionSize]="collectionSize" [(page)]="page" [pageSize]="pageSize">
</ngb-pagination>
</div>
班级:
export class CategoryListComponent implements OnInit {
// Original array
jobs: JobId[];
// Pagination
page = 1;
pageSize = 20;
collectionSize = 0;
// Filtered array
searchedJobs$: Observable<JobId[]>;
// Value received from service to filter the array
filter = new FormControl('');
constructor(
private jobService: JobService,
private searchService: SearchService
) {
// This is for filtering
this.searchedJobs$ = this.filter.valueChanges.pipe(
startWith(''),
map(text => this.search(text))
);
}
ngOnInit() {
// Receives an array of jobs
const subJobs = this.jobService.getAll().subscribe(res => {
this.jobs = res;
// Updates the collectionSize
this.collectionSize = this.jobs.length;
});
// This is for filtering. I receives a value from a component using a service as intermediary
this.searchService.currentMessage.subscribe(message => {
this.filter.setValue(message);
});
}
// This is for filtering
search(text: string): JobId[] {
const array = this.jobs
.filter(job => {
return job.location.toLowerCase().includes(text.toLowerCase())
|| job.position.toLowerCase().includes(text.toLowerCase())
|| job.company.toLowerCase().includes(text.toLowerCase());
});
// Updates the collectionSize
this.collectionSize = array.length;
return array;
}
// I don't know how/where to implement this method
get jobsFiltered(): JobId[] {
return this.jobs
.slice((this.page - 1) * this.pageSize, (this.page - 1) * this.pageSize + this.pageSize);
}
}
我不知道这是否是有史以来最好/最简单的代码。
我的目标是对表格进行过滤和分页。能够正确过滤和使用分页按钮以查看更多结果。