Search code examples
angularvmware-clarity

Render Multiple grids on the same page with different dataset


I have two datagrids on the same page. The goal is to have each datagrid make an API call with different parameters and render data, so they function individually.

I am able to have the grids make different API calls and get data. But, I am facing an issue setting the data individually to those grids.

I created a StackBlitz example, demonstrating the issue.

app.component.ts

refresh(state: ClrDatagridStateInterface, postId) {
      this.loading=true;
      const filters: { [prop: string]: any[] } = {};
      if (state.filters) {
        for (const filter of state.filters) {
          const { property, value } = <{ property: string; value: string }>filter;
          filters[property] = [value];
        }
      }
      if (state.page != undefined && state.page != undefined)
      {
        setTimeout(() => {
        this.loading = true;
        this.getData(postId, state.page.from, state.page.size );
        });
      }
  }

    getData(postId:string, page: number, size:number  ) {
    this.userAccounts$ = this.informationService.GetUserAccounts(postId);
      this.userAccounts$
        .subscribe((data) => {
            this.users = JSON.parse(JSON.stringify(data)) || null
            this.loading = false
        }
        );
    }

I am generating the grids in a for loop using an array of Post Ids.

posts:any = ["1","4"];

Each grid is supposed to make an API call with that postId,

Ex: https://jsonplaceholder.typicode.com/comments?postId=1
Ex: https://jsonplaceholder.typicode.com/comments?postId=4

to get postId and email and display it in the grid. Each grid needs to function individually, whether it is sorting or filtering or paging.

The getData function is setting API data globally for use for both grids. How can I can set it for the grids individually?


Solution

  • You are always settting this.users = JSON.parse(JSON.stringify(data)) || null in your subscription, and always looping over users. So basically you're not creating a different property to hold the data.

    Generally, I would argue against this approach. What I would do is encapsulate the whole datagrid one time as a component with an input to accept the configuration data (seems like postId). Then reuse the component twice to get your duplicate datagrids that are individually encapsulated. Otherwise, you've got a lot of logic bleeding between both datagrids and it could be hard to manage.