MatTableDataSource failing to showcase remote dataSource in mat-table component

I am experiencing issues while trying to incorporate a component using mat-table with data source from a Remote Server. The table is not displaying the data as expected.

html

    <div class="mat-elevation-z8">
  <mat-form-field>
    <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
  </mat-form-field>

  <table mat-table [dataSource]="dataSource" matSort style="width: 100%;">

    <ng-container matColumnDef="accountType">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Account Type </th>
      <td mat-cell *matCellDef="let e"> {{e.accountType}} </td>
    </ng-container>

    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> ID </th>
      <td mat-cell *matCellDef="let e"> {{e.id}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
    <tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
  </table>
  <mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
</div>

ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatTableDataSource, MatSort } from '@angular/material';

import { HeadAccount } from '../../Data/HeadAccount';
import { HeadAccountsService } from '../../Services/head-accounts.service';

import { AfterViewInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-head-accounts',
  templateUrl: './head-accounts.component.html',
  styleUrls: ['./head-accounts.component.css']
})
export class HeadAccountsComponent implements OnInit {

  constructor(private haser: HeadAccountsService) { }

  ngOnInit() {
    this.gets();
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  has: HeadAccount[];
  dataSource = new MatTableDataSource(this.has);
  columnsToDisplay: string[] = ['accountType', 'id'];
  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  gets(): void {
    this.haser.gets()
      .subscribe(has => this.has = has);
  }
  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}

However, if I modify dataSource directly to has, such as [dataSource]="has", the data appears but other features like pagination, sorting, and filtering are not working properly.

In App Module, ensure that you have imported and exported

MatTableModule, MatPaginatorModule,
and MatSortModule.

Answer №1

After integrating the lodash library, I utilized _.castArray function instead of [...data] even though both options were available. Additionally, I found it necessary to use a setTimeout function to encapsulate my sort and paginator tasks, although this step might not be relevant in your specific case.

this.dataSource = new MatTableDataSource(_.castArray(data));
    setTimeout(()=> this.dataSource.sort = this.matSort);
    setTimeout(()=> this.dataSource.paginator = this.paginator);

Answer №2

By shifting the code block originally placed within ngAfterViewInit() to be inside the service's .subscribe method, I was able to successfully resolve the issue.

The snippet below showcases the updated implementation:

this.service.getData()
  .subscribe(data => {
    this.dataSource = new MatTableDataSource(data);
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  });

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

Utilize the identical element

Incorporating the JwPaginationComponent into both my auction.component and auctiongroup.component has become a necessity. To achieve this, I have created a shared.module.ts: import { NgModule } from '@angular/core'; import { JwPaginationCompon ...

What is the reason behind prettier's insistence on prefixing my IIAFE with ";"?

I've encountered async functions in my useEffect hooks while working on a JavaScript project that I'm currently transitioning to TypeScript: (async ():Promise<void> => { const data = await fetchData() setData(data) })() Previously, ...

Customizing number input types in Angular 2 - the perfect solution

Attempting to incorporate a time picker using HTML5 input type number in Angular2. The code snippet below illustrates the setup: <input type="number" [(ngModel)]="hour" (change)="checkHours();" name="one" min="1" max="12"> <input type="number" ...

Using Conditionals in React Props

In the process of developing a component that requires two props, inside and position, I've encountered an interesting dilemma. When inside is set to true, then position is limited to left or bottom. However, if inside is set to false, then position c ...

How can I capture the click event on the oktext in Ionic?

When using Ionic, I have a select button with options for okText and cancelText. The issue I am facing is that when I click on okText, the menu closes as expected due to this attribute. However, I am interested in implementing it through click events. Belo ...

How can we avoid excessive re-rendering of a child component in React when making changes to the parent's state?

In my React application, I am facing a situation where a parent component controls a state variable and sends it to a child component. The child component utilizes this state in its useEffect hook and at times modifies the parent's state. As a result, ...

Tips for Sending Variables in HTTP Requests in Angular 9

'''Is there a way to pass fromDateTime and toDateTime as parameters in this link?''' export function MSALInterceptorConfigFactory(): MsalInterceptorConfiguration { const protectedResourceMap = new Map<string, Array& ...

Can an interface be expanded within an object array using React and Typescript?

I am working with two different interfaces: Interface 1: interface ILineItemProps { state: 'OPENED' | 'COMPLETED' | 'CANCELLED' | 'PENDING'; } Interface 2: interface IProps { steps: [ { ...

The variable in Angular stopped working after the addition of a dependent component

Currently, I am working with Angular and have implemented two components. The first component is a navigation bar that includes a search bar. To enable the search functionality in my second component (home), I have added the following code: HTML for the n ...

The FirebaseX Ionic native plugin received 2 arguments instead of the expected 3-4

Trying to implement Firebase Phone Auth with the FirebaseX plugin, I encountered an issue. Here is the code snippet I used: async getVerificationCode(): void { const res:any = await this.firebaseX.verifyPhoneNumber('+16505553434', 60); ...

Using Typescript to iterate through an array of objects and modifying their keys using the forEach method

I have an object called 'task' in my code: const task = ref<Task>({ name: '', description: '', type: undefined, level: 'tactic', participants: undefined, stages: undefined, }); export interface Tas ...

Creating a JSON schema for MongoDB using a TypeScript interface: a step-by-step guide

In order to enhance the quality of our data stored in MongoDB database, we have decided to implement JSON Schema validation. Since we are using typescript in our project and have interfaces for all our collections, I am seeking an efficient method to achie ...

What is the best way to effectively handle the proxying of objects across multiple levels?

As illustrated in a Stack Overflow thread, utilizing Proxy objects is an effective method for monitoring changes in an object. But what if you need to monitor changes in subobjects? In such cases, you will also have to proxy those subobjects. I am curren ...

Implementing Observable in NativeScript with TypeScript - A Step-by-Step Guide

Recently, I delved into the world of native-script framework and decided to dive into the "Get Started with JavaScript" tutorial provided on their official website. My background in Java has made me more comfortable with typescript, so I attempted to swap ...

Failing Cypress component test: When leveraging an index.ts file for importing and exporting services

Tech stack: Angular v15 and Cypress v12. My example component that I'm testing: import { Component } from '@angular/core'; import { UserHttp } from '../../services'; @Component({ selector: 'example-view', templateUr ...

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

Encountered an issue with JSON serialization while using getServerSideProps in Next.js and TypeScript to retrieve products from the Stripe Payments API

Encountered Issue on Localhost Error: The error occurred while serializing .products returned from getServerSideProps in "/". Reason: JSON serialization cannot be performed on undefined. Please use null or exclude this value. Code Sample import ...

The recognition of Angular ngrx union type actions is hindered by discrepancies in constructors

The actions classes and union type are displayed below. Unfortunately, these actions are not being recognized during the application's execution. export class Login implements Action { readonly type = LOGIN; constructor( public payload: { ...

Tips for fixing the TypeError related to hasOwnProperty in your index.tsx file

I need assistance setting up a basic frame for my TypeScript project as I am having trouble compiling it. Any guidance would be greatly appreciated. The error I am encountering is: in ./app/index.tsx Module build failed: TypeError: Cannot convert undefin ...

What methods can I use to guarantee that a cloned HTML element retains a specific property during Unit Testing?

During my HTML cloning process, I am using the following code snippet: var clone = document.getElementById('tempID').cloneNode(true); After creating the clone, I need to modify its ID by assigning a new unique identifier with clone['id&apo ...