Clear pagination - results generated by the clr-dg-page-size component

I'm currently developing an Angular 8 application using Clarity UI.

Within my app, I have implemented a datagrid with pagination. My challenge lies in fetching data after changing the number of items per page, as there is no output provided by the Clarity components for this action. The only output available is for changing pages.

Below is the HTML snippet that I am working with:

<clr-dg-footer>
    <clr-dg-pagination #pagination [clrDgPageSize]="itemsPerPage" [clrDgTotalItems]="totalElements" [clrDgLastPage]="totalPages"
    (clrDgPageChange)="onChangePage($event)">
      <clr-dg-page-size [clrPageSizeOptions]="[5,20,50,100]" (change)="onItemsPerPageChange($event)">Vehicles per page</clr-dg-page-size>
      {{pagination.firstItem + 1}} - {{pagination.lastItem + 1}}
      of {{pagination.totalItems}} vehicles
    </clr-dg-pagination>
  </clr-dg-footer>

This is how I currently handle the item selection change:

onItemsPerPageChange(event) {
    let newValue = +event.target.value.slice(3);
    if(this.itemsPerPage !== newValue) {
      this.itemsPerPage = newValue;
      this.fetchCars();
    }
  }

While this approach gets the job done, I am aware that it may not be the most optimal solution.

If you have any suggestions on a better way to achieve this functionality, please share your ideas as I am currently stumped.

Answer №1

When working with Clarity's datagrid, a common approach is to utilize the ClrDatagridStateInterface in conjunction with the (clrDgRefresh) binding within the datagrid template.

To explore further, refer to Clarity's Server-Driven datagrid API or check out this demo on Stackblitz for clarity-dg-server-driven.

In your component, leverage the functionalities of ClrDatagridStateInterface:

class MyComponent {
    users: User[];
    total: number;
    loading: boolean = true;

    refresh(state: ClrDatagridStateInterface) {
        this.loading = true;
        ...
        this.inventory.filter(filters)
            .sort(<{by: string, reverse: boolean}>state.sort)
            .fetch(state.page.from, state.page.size)
            .then((result: FetchResult) => {
                this.users = result.users;
                this.total = result.length;
                this.loading = false;
            });
    }

Ensure to bind (clrDgRefresh) to your refresh method in the template:

<clr-datagrid (clrDgRefresh)="refresh($event)" [clrDgLoading]="loading">
    <clr-dg-column>User ID</clr-dg-column>
    <clr-dg-column [clrDgField]="'name'">Name</clr-dg-column>
    <clr-dg-column [clrDgField]="'creation'">Creation date</clr-dg-column>
    <clr-dg-column [clrDgField]="'pokemon'">Pokemon</clr-dg-column>
    <clr-dg-column [clrDgField]="'color'">Favorite color</clr-dg-column>

    <clr-dg-row *ngFor="let user of users">
        <clr-dg-cell>{{user.id}}</clr-dg-cell>
        <clr-dg-cell>{{user.name}}</clr-dg-cell>
        <clr-dg-cell>{{user.creation | date}}</clr-dg-cell>
        <clr-dg-cell>{{user.pokemon.name}}</clr-dg-cell>
        <clr-dg-cell>
            <span class="color-square" [style.backgroundColor]="user.color"></span>
        </clr-dg-cell>
    </clr-dg-row>

    <clr-dg-footer>
        {{pagination.firstItem + 1}} - {{pagination.lastItem + 1}}
        of {{total}} users
        <clr-dg-pagination #pagination [clrDgTotalItems]="total"></clr-dg-pagination>
    </clr-dg-footer>
</clr-datagrid>

Refer to the sources of Clarity's server-driven example on GitHub.

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

Is it possible to verify type equality in Typescript?

If the types do not match, I want to receive an error. Here is an example of an object: const ACTIVITY_ATTRIBUTES = { onsite: { id: "applied", .... }, online: { id: "applied_online", .... }, ... } as co ...

Is it possible to determine the specific type of props being passed from a parent element in TypeScript?

Currently, I am working on a mobile app using TypeScript along with React Native. In order to maintain the scroll position of the previous screen, I have created a variable and used useRef() to manage the scroll functionality. I am facing an issue regardi ...

how to share a variable across multiple ts files in an Angular project

In the home.component.ts file, I have a variable named name that I want to access globally in all files. Can anyone please suggest how can I achieve this? Below is the code snippet: app.component.html <nav aria-label="breadcrumb"> <ol class= ...

What is the process for invoking an External Javascript Firestore function within a Typescript file?

Trying to figure out how to integrate a Firestore trigger written in an external JavaScript file (notifyNewMessage.js) into my TypeScript file (index.ts) using Node.js for Cloud functions. Both files are located in the same directory: https://i.stack.imgu ...

Transfer items on a list by dragging and dropping them onto the navigation label of the target component

I'm currently exploring how to move an element from a list to a <div> and then see it transferred to another list. The objective is to allow users to drag items from one list onto the labels in a sidebar navigation, causing the item to switch t ...

The statement 'typeof import("...")' fails to meet the requirement of 'IEntry' constraint

When trying to run npm run build for my NextJS 13 app, I encountered the following type error: Type error: Type 'typeof import("E:/myapp/app/login/page")' does not satisfy the constraint 'IEntry'. Types of property 'def ...

Migrating image information from Angular version 14 to Asp.Net Core 6.0 Rest Api

When transferring product model data from Angular to a REST API using FormData, there is an images array included in the product data. Upon receiving this product in the REST API, the images data is accessed using Request.Form.Files. The images are then se ...

From JSON Schema to ng2-tree treemodel: Implementing in Angular 4

I am looking to create a dynamic Tree view of JSON in the UI that can be edited and saved on the fly. Currently, I am experimenting with TreeModel in Angular 4, but I'm facing challenges because the JSON schema and TreeModel schema are different. I ...

What is the process for generating an object type that encompasses all the keys from an array type?

In my coding journey, I am exploring the creation of a versatile class that can define and handle CRUD operations for various resources. The ultimate goal is to have a single generic class instance that can be utilized to generate services, reducer slices, ...

Brand new installation of npm and nodePackageManager

I've recently delved into Angular 2 development, but I'm facing some challenges running the Angular 2 Quickstart project smoothly. The culprit seems to be a slew of npm dependency errors. Is there a way for me to globally uninstall all previousl ...

Weekday Filter in Angular 2

Looking to utilize the date pipe feature in Angular 2, specifically aiming for output that only includes the weekday name, such as "Wednesday." I am aware of the typical method to achieve this: {{ strDate | date :'fullDate' }} This would resul ...

How to Retrieve Superclass Fields in Angular 5 Component

I have a superclass that provides common functionality for components. export class AbstractComponent implements OnInit { public user: User; constructor(public http: HttpClient) { } ngOnInit(): void { this.http.get<User>(& ...

The autoimport feature is not supported by the Types Library

My latest project involves a unique library with only one export, an interface named IBasic. After publishing this library on npm and installing it in another project, I encountered an issue. When attempting to import IBasic using the auto-import feature ( ...

Tips for ensuring a method is not invoked more than once with identical arguments

I'm grappling with a challenge in JavaScript (or typescript) - ensuring that developers cannot call a method multiple times with the same argument. For instance: const foo = (name: string) => {} foo("ABC") // ok foo ("123") ...

Troubleshooting problems encountered in Nest.js due to modifications made within a service.ts file

I'm currently working on a Nest.js project and here is the content of the automobile.service.ts file: import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Car } from './enti ...

Problems encountered while building TypeScript on Azure's Hosted Agent

I'm currently working on an ASP.NET MVC application built in .Net5 that utilizes TypeScript files and includes NuGet package references for the following: <PackageReference Include="BuildBundlerMinifier" Version="3.2.449" /> ...

How to capture and log request and response data when using the HttpService in NestJS?

Is there a way to log requests, responses, and errors using the HttpService within the HttpModule? In the past, I have used Interceptors with AXIOS. While HttpService wraps axios, I'm having trouble adding interceptors. There doesn't seem to be ...

When a 404 error is thrown in the route handlers of a Next.js app, it fails to display the corresponding 404 page

I am encountering an issue with my route handler in Next.js: export async function GET(_: Request, { params: { statusId } }: Params) { const tweetResponse = await queryClient< Tweet & Pick<User, "name" | "userImage" | &q ...

Travis CI's TypeScript build process detects errors before Mocha has a chance to catch them

Instead of a bug, the TypeScript compiler is doing its job but causing my Travis builds to fail. In my package, I have a function named completeRound which accepts a number as its first argument and 3 optional arguments. Since it's in TypeScript, I s ...

Issue with angular oidc-client library's automaticSilentRenew functionality

I'm currently implementing oidc authentication using "oidc-client" version 1.10.1. Below is the configuration I have set up for the userManager: const settings = { authority: (window as any).__env.auth.authority, //OAuth 2.0 authorization end ...