Error in integrating ng2-bootstrap pagination with a bootstrap table

I am currently working on incorporating the ng2-bootstrap pagination component with a bootstrap table.

The bootstrap table I have is populated using the 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 contents of rows are determined by the pagination component: I have an array named data that contains multiple entries for the table. The length of the array determines the totalItems displayed in the pagination component:

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

The variable rows in the table only displays the entries from the current page. This is achieved through utilizing 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);
    }

Everything seems to be working fine... However, when entries are removed from the data array while the pagination bar is on the last page, the following error message appears in the console:

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

You can experiment with a live example here: http://plnkr.co/edit/5zxamBiWISBpEmXYP5UK?p=preview Simply click the last button and then cut data.

Any suggestions or advice?

Answer №1

To find a solution, I made adjustments to the cutData function. I included a line that resets the current page to 1 before cutting the data:

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

After implementing this change, everything started functioning as intended.

Another approach (referenced here for a similar issue) involves manually triggering change detection for the component after altering 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();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The exit code 1 was triggered in the npm-lifecycleindex.js file at line 285,

0 silly lifecycle <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bac9ced5c8d194c9cadbfa8b948a948a">[email protected]</a>~build.prod: Args: [ '/d /s /c', 10 silly lifecycle 'gulp build.prod --color --en ...

How should one properly format an array of objects with elements that are different types of variations?

I am currently developing a versatile sorting module using TypeScript. This module will take in an array of data objects, along with a list of keys to sort by. Once the sorting process is complete, the array will be sorted based on the specified keys. To ...

Broaden the current category within the MUI Theme

I am attempting to enhance the current options within MUI's theme palette by adding a couple of properties. Take a look at this example: declare module @material-ui/core/styles/createMuiTheme { interface CustomOptions extends SimplePaletteColorOptio ...

Creating distinct "ViewContainerRef" containers for separate tabs in mat-tab within Angular

I have created a runtime component module that generates dynamic components by binding HTML data and functions fetched from an API call. These components are then loaded into a container within tabs, which are also dynamically created based on the data. Th ...

When there is data present in tsconfig.json, Visual Studio Code does not display errors inline for TypeScript

After creating an empty .tsconfig file (consisting solely of "{ }"), Visual Studio Code immediately displays errors both inline and in the "problems" section. Interestingly, when I populate the tsconfig.json file with data, these errors disappear. Is there ...

Is there a way to access URL parameters in the back-end using Node.js?

How can I extract querystring parameters email, job, and source from the following URL? I want to use these parameters in my service class: @Injectable() export class TesteService{ constructor(){} async fetchDataFromUrl(urlSite: URL){ ...

Adding a project to TFS source control using Visual Studio Code: a step-by-step guide

Looking for guidance on adding an Angular 4 project developed with Visual Studio Code (version 1.18.0) to TFS source control. I've already installed the TFS extension (version 0.6.0) in Visual Studio Code, but unsure how to map the project folder to T ...

Encountering TypeScript errors with React-Apollo when using GraphQL to pass props to a higher order component

I've encountered some challenges while attempting to link a React class component with my local Apollo cache data. Following the guidelines outlined here, I have run into issues where VSCode and Webpack are generating errors when I try to access data ...

What are the steps to compile Angular8 code generated at runtime?

Currently, I am dynamically creating Angular code on the fly. This involves using an SVG library to generate a vector graphic with Angular code directives such as (click)='myMethod()'. These directives call methods that have been statically defin ...

pnpm, vue, and vite monorepo: tackling alias path imports within a workspace package

I am in the process of creating a monorepo for UI applications that utilize shared components and styles with pnpm, typescript, vue, and vite. While attempting to streamline development and deployment using pnpm's workspace feature, I am encountering ...

What is the process for incorporating a Static Class into a Declaration File in TypeScript?

I'm in the process of developing a UMD library using TypeScript. The first class I have created is a static one with a method. The name of my Library is SuperLib and here is the code snippet: export class Security { static userExists ( user: string ...

Error: Attempting to access property 'baseHref' of an undefined value is not possible

Creating a webpack configuration for Angular 7 has been my recent project. I found a helpful tutorial on how to customize build configuration at this link. I decided to use the @angular-builders package for this task. Upon checking my index.html file, I m ...

Trigger event in App.component.ts after child view initialization in Angular 8 and higher versions

I've been encountering an issue while trying to incorporate HubSpot page tracking into my Angular 8+ application. Currently, I'm tapping into the NavigationEnd event on my router within app.component.ts. The problem arises when each child compone ...

Having numerous occurrences of the identical root application in Angular 2

Our team has been successfully integrating Angular 2 into a legacy page, gradually enhancing its user-friendliness by replacing prerendered backend widgets with angular modules. However, we have encountered a challenge that I am unsure how to address: I h ...

How can I clear the div styling once the onDismiss handler has been triggered

Seeking assistance with resetting a div on a Modal after it has been closed. The issue I am facing with my pop-up is that the div retains the previous styling of display: none instead of reverting to display: flex. I have searched for a solution without su ...

The method for renaming a namespace when exporting it in Typescript

Suppose I am using a third-party namespace Foo in my Typescript code. I intend to create some utility functions for this module within a module called Utility.Foo. The issue here is that the original Foo would be hidden from functions defined inside Util ...

Encountering a crash when trying to create a form within a subscription in Angular 2 due to the formGroup being

I have data stored in my Firebase database that I want to use in a form using FormBuilder. Although it generally works fine, I often encounter errors saying formGroup expects a FormGroup instance. Please pass one in.. What confuses me is that the error oc ...

Need help with resolving index.js?

Recently, I built a standard angular + asp.net application without making any modifications. However, when attempting to launch dotnet, an error message is displayed. I have ensured that I am using the latest versions of Angular, DotNet, Npm, and Node. A ...

What is the reason behind TypeScript requiring me to initialize a property even though I am retrieving its value from a local reference?

I am just beginning to explore Angular. This is the template for my custom component: <div class="row"> <div class="col-xs-12"> <form action=""> <div class="ro"> <d ...

Working with JSON data in Angular 2 constructor

When sending a JSON response from the server, it is in the format shown below: {id: Int, name: String, childJSON: String} I want to map this data to the following TypeScript classes: export class Student{ constructor(public id: string, ...