首页 文章

ng2-bootstrap分页和引导程序表集成错误

提问于
浏览
3

我正在尝试集成ng2-bootstrap pagination component和bootstrap表 .

我有一个简单的bootstrap表加载ngFor指令:

<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>

rows 内容由分页组件决定:我有一个名为 data 的数组,其中包含表的一堆条目 . 数组长度用于确定分页组件的 totalItems

<pagination class="pagination-sm"
            [(ngModel)]="page"
            [totalItems]="data.length"
            [itemsPerPage]="itemsPerPage"
            [maxSize]="maxSize"
            [boundaryLinks]="true"
            (pageChanged)="onPageChange($event)">
</pagination>

表的 rows 变量仅包含当前页面的条目 . 这是通过使用分页组件提供的 pageChange 事件来完成的:

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);
    }

到目前为止一直这么好......问题是可以从 data 数组中删除条目 . 如果分页栏指向最后一页,然后从 data 数组中删除条目,则在控制台中显示以下错误:

Expression 'rows in App@9:8' has changed after it was checked.

可以在此处找到实时示例:http://plnkr.co/edit/5zxamBiWISBpEmXYP5UK?p=preview只需单击 last 按钮,然后单击 cut data .

有什么建议?

1 回答

  • 3

    作为一种解决方法,我决定稍微更改 cutData 功能 . 在每次数据切割之前,当前页面将重置为1:

    cutData(){
      this.page = 1;
      this.onPageChange({page: this.page, itemsPerPage: this.itemsPerPage})
      this.data = this.data.slice(0, this.data.length/2);
    }
    

    现在一切似乎都按预期工作了 .

    Another option (如同类似问题所述here)是在 rows 更改后手动触发组件的更改检测:

    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();
    }
    

相关问题