What is the best way to display data from an API in a component table?

Currently, I am working with Angular and Material-Angular to display data from the Reqres API (https://reqres.in). Despite building a table with pagination, I encountered an issue with my pagination functionality not working as expected.

To manage the data retrieval and storage, I have set up a service and model using HttpClient. Within the component class, I have defined two variables for this purpose: users: User[] and

dataSource = new MatTableDataSource<User>(this.user)
.

import { Component, OnInit, ViewChild } from '@angular/core';
import { User } from '../config/user.module';
import { DataService } from '../data.service';
import { MatPaginator, MatTableDataSource } from '@angular/material';

@Component({
  selector: 'app-users-list',
  templateUrl: './users-list.component.html',
  styleUrls: ['./users-list.component.sass']
})
export class UsersListComponent implements OnInit {
  users: User[];
  page: number;

  displayedColumns = ['Id', 'FirstName'];
  dataSource = new MatTableDataSource<User>(this.users);

  constructor(private dataService: DataService) { }

  @ViewChild(MatPaginator) paginator: MatPaginator;

  ngOnInit() {
    this.dataSource.paginator = this.paginator;

    this.showUsers();
  }

  showUsers() {
    this.page = 1;
    this.dataService.getUsers(this.page)
      .subscribe(res => {
        this.users = res['data'];
      });
  }

}

In terms of the template.html file:

<section class="list">
  <table mat-table [dataSource]="users" class="mat-elevation-z8 table">
    <ng-container matColumnDef="Id">
      <th mat-header-cell *matHeaderCellDef>
        <span class="table-header">No.</span>
      </th>
      <td mat-cell *matCellDef="let user">
        <span class="table-value">{{user.id}}</span>
      </td>
    </ng-container>
    <ng-container matColumnDef="FirstName">
      <th mat-header-cell *matHeaderCellDef>
        <span class="table-header">Name</span>
      </th>
      <td mat-cell *matCellDef="let user">
        <span class="table-value">{{user.first_name}}</span>
      </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
  <mat-paginator [pageSizeOptions]="[3]" showFirstLastButtons></mat-paginator>
</section>

Upon changing users to dataSource in the HTML file:

<table mat-table [dataSource]="HERE" class="mat-elevation-z8 table">
, no results are displayed in the table. It seems like the declaration of dataSource is correct and it should fetch data from users, but that's not happening. If I switch back to using users, everything displays correctly, yet I require dataSource for pagination purposes. Could it be that the issue lies with the timing of when data is present in users during invocation?

Current Setup: Angular-CLI 7

Answer №1

Make sure to bind your dataSource directive to an object of type MatTableDataSource, not users. This will assist you with sorting and pagination functionalities.

  <table mat-table [dataSource]="dataSource" class="mat-elevation-z8 table">

Next, update the MatTableDataSource object where you have subscribed to the observable returned by getUsers method.

showUsers() {
this.page = 1;
this.dataService.getUsers(this.page)
  .subscribe(res => {
    this.datasource = new MatTableDataSource(res['data']);
  });

Another option is to utilize the renderRows method. This can be beneficial if you are making multiple API calls, as it updates the rows for any changes made.

Check out the official stackbitz example here: https://stackblitz.com/edit/angular-mat-table-render-rows?file=app%2Ftable-filtering-example.ts

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

Improving the clarity of Jest snapshot test logs using styled from MUI

Currently, I am working with MUI v5 along with styled components and Jest snapshot testing. I am looking for a way to improve the logs generated when a snapshot test fails. Below is an example of the component I am dealing with: const styledProperties = n ...

In a specific Angular project, the forget password feature is experiencing issues with sending email links in the Chrome browser. Interestingly, this issue only occurs the first

I'm currently working on an Angular 6 application that has been deployed with the domain "www.mydomain.com/". All the routes are functioning properly, such as "www.mydomain.com/dashboard" and "www.mydomain.com/products". However, there is an issue w ...

The Mat-Card inside the Mat-Table fails to expand to its full width when using overflow-x property

When I inserted a mat-card in a mat-table and set the width to 100%, I noticed that when scrolling with overflow-x from left to right, the whole wrapper was not completely filled with the mat-card. Can anyone suggest CSS optimizations for this issue? Here ...

Utilizing Nested ControlGroups in Angular2 rc1: A Comprehensive Guide

Seeking assistance with understanding the functionality of a control group. Attempting to implement something similar to this: app.component.ts: import { Component, OnInit } from "@angular/core"; import { FORM_DIRECTIVES, FormBuilder, ControlGroup } from ...

Managing recurring days and times in Angular and retrieving the next scheduled time

I'm currently working on a new feature that will allow users to set multiple wake alarms for specific days and times. For example, they may want alarms to go off on Mondays, Wednesdays, and Fridays at 7:00 AM and 8:00 PM, and on Tuesdays and Thursdays ...

React-snap causing trouble with Firebase

I'm having trouble loading items from firebase on my homepage and I keep running into an error. Does anyone have any advice on how to fix this? I've been following the instructions on https://github.com/stereobooster/react-snap and here is how ...

RxJs: Generating an observable based on changes in a field's value

Is there a way to generate an Observable using the variable this.pending as its source? I'm looking to create an Observable that will produce a new feed each time the value of this.pending changes. For example, if I update this.pending to be false i ...

Transitioning from angular version 5.2 to the latest angular 6.1 version

Currently, I find myself on node 8.11 and utilizing VS code. The project was originally built in version 5.2.5 but has been inactive for some time now. Within my project, the following modules are present: import { BrowserModule } from '@angular/plat ...

Does the onAuthStateChanged listener in firebase trigger immediately upon user login or logout?

//initialize auth change listener useEffect(() => { auth.onAuthStateChanged((user) => { if (user) { router.replace('/') } }) setInitializing(false) }, []) //*handled by login button const login = asy ...

Tips for denoting unnecessary non-null assertions in Typescript

Incorporated this wrapper (source) into the project I'm currently working on: export function expectToBeDefined<T>( arg: T, ): asserts arg is Exclude<T, undefined> { expect(arg).toBeDefined(); } The objective is to eliminate the usage ...

Unable to retrieve jwt tokens transmitted from the frontend to the backend

Having just started learning Django and simplejwt, I'm facing an issue with retrieving tokens sent from our Angular frontend labeled as "app_token" and "access_token". Despite trying variations like "HTTP_APP_TOKEN" and "HTTP_ACCESS_TOKEN", as well as ...

Remove multiselect label in PrimeNG

I am attempting to change the multiselect label of selected items and replace it with a static default label. Here is what it currently shows: https://i.sstatic.net/qBNHG.png This is what I have tried: .p-multiselect-label { visibility: collapse; ...

Guide on sending uploaded files and JSON data to an API using Angular2

Looking to send a file (or files) along with other json data, but facing limitations. After some research, it seems that the only options are sending files alone or converting them to base64 before including in the JSON for API transfer (unconfirmed). Ex ...

Retrieve a specific subdirectory from the bundle

I've developed a Typescript package with the following file structure: package.json src/ index.ts common/ index.ts sub/ index.ts My goal is to import certain modules from the package like this: import {...} from '<package>&ap ...

Utilizing the "or" operator in Typescript alongside Omit<> - A Comprehensive Guide

In the following code snippet: type WithOr = {a:string} & ({b?:true, c?:never} | {b?:false, c:number}) type Ommited = Omit<WithOr, 'a'> const m1: Ommited = {b: true}; const m2: WithOr = {...m1, a: 'a'} An error will be encou ...

Step-by-step guide to setting up Next.js with TailwindCSS using JavaScript explicitly

Currently, I am working on a Next.js project where all the files have the extension .tsx (TypeScript). Although TypeScript is similar to Java, I prefer to have the file ending as .js. I attempted to modify the command (npx create-next-app -e with-tailwin ...

Unlocking the potential of Bootstrap 4 pop ups and modals within an Angular 6 project

Angular.json "styles": [ "./node_modules/bootstrap/dist/css/bootstrap.min.css", "./node_modules/ngx-bootstrap/datepicker/bs-datepicker.css", "src/styles.css" ], ...

Components that rely on Angular's properties

I currently have three main components in my project: CategoryComponent - responsible for displaying a list of categories ListComponent - displays elements based on the selected category ScreenComponent - combines MenuComponent and ContentComponent toget ...

Assign a variable within a Vue composition file

I'm diving into the world of composition API in Vue and I'm uncertain if my approach is breaking any established patterns. I have a desire to initialize a variable directly within the composition file: GameLogic.ts export default function () { ...

Why can't Angular iterate through objects using ngFor in Typescript?

Here's what I currently have: public posts: QueryRef<PostsInterface>; this.posts = this._postService.get(); //in ngOnInit In my HTML file, it looks like this: <mat-card *ngFor="let post of posts | async"> This allows me to display eac ...