问题
I'm trying to integrate ng2-bootstrap pagination component and bootstrap table.
I have a simple bootstrap table that is loaded with ngFor directive:
<tr>
<th *ngFor="#col of cols">{{col.header}}
</tr>
</thead>
<tbody>
<tr *ngFor="#row of rows">
<td *ngFor="#col of cols">{{row[col.field]}}</td>
</tr>
</tbody>
The rows
content is determined by the pagination component:
I have an array called data
that contains a bunch of entries for the table. The array length is used to determined the totalItems
of the pagination component:
<pagination class="pagination-sm"
[(ngModel)]="page"
[totalItems]="data.length"
[itemsPerPage]="itemsPerPage"
[maxSize]="maxSize"
[boundaryLinks]="true"
(pageChanged)="onPageChange($event)">
</pagination>
The table's rows
variable contains only the entries of the current page. This is done by using the pageChange
event provided by the pagination component:
onPageChange(page:any) {
let start = (page.page - 1) * page.itemsPerPage;
let end = page.itemsPerPage > -1 ? (start + page.itemsPerPage) : this.data.length;
this.rows = this.data.slice(start, end);
}
So far so good...
The problem is that entries can be removed from the data
array.
If the pagination bar is pointing to the last page and then entries are removed from the data
array, the below error is shown in console:
Expression 'rows in App@9:8' has changed after it was checked.
A live example can be found here:
http://plnkr.co/edit/5zxamBiWISBpEmXYP5UK?p=preview
Just click the last
button and then cut data
.
Any advice?
回答1:
As a workaround, I decided to change the cutData
function a little bit.
Before each data cut, the current page is reset to 1:
cutData(){
this.page = 1;
this.onPageChange({page: this.page, itemsPerPage: this.itemsPerPage})
this.data = this.data.slice(0, this.data.length/2);
}
Now everything seems to work as expected.
Another option (as mentioned here for a similar issue) is to manually trigger change detection for the component after rows
change:
constructor(private cd: ChangeDetectorRef) {}
(...)
onPageChange(page:any) {
let start = (page.page - 1) * page.itemsPerPage;
let end = page.itemsPerPage > -1 ? (start + page.itemsPerPage) : this.data.length;
this.rows = this.data.slice(start, end);
this.cd.detectChanges();
}
来源:https://stackoverflow.com/questions/36874587/ng2-bootstrap-pagination-and-bootstrap-table-integration-error