What is the best method for showcasing information within an Angular Material table?

When using Angular material to display a list, I am facing an issue where the content of the list is not being displayed but the header is.
Component:

export class CompaniesComponent implements OnInit {
  displayedColumns: string[] = ['id'];
  data: Company[] = [];
  isLoadingResults = true;

  constructor(private api: ApiService) { }

  ngOnInit() {
    this.api.getAllCompanies()
    .subscribe(res => {
      this.data = res;
      console.log(this.data);
      this.isLoadingResults = false;
    }, err => {
      console.log(err);
      this.isLoadingResults = false;
    });
  }

}

html:

<div class="example-container mat-elevation-z8">
  <div class="example-loading-shade"
       *ngIf="isLoadingResults">
    <mat-spinner *ngIf="isLoadingResults"></mat-spinner>
  </div>
  <div class="mat-elevation-z8">
    <table mat-table [dataSource]="data" class="example-table"
           matSort matSortActive="id" matSortDisableClear matSortDirection="asc">

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

      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    </table>
  </div>
</div>

result: https://i.sstatic.net/BsFJ8.png

list element format (json):

   {
        "id": 21,
        "companyName": "iErjVkVG",
        "companyDescription": "12345",
        "rating": 1,
        "companyValuation": 756,
        "salary": 3.22,
        "professionalGrowth": 2.56,
        "companyBenefits": 2.44,
        "communicationWithColleagues": 2.67,
        "educationSector": 3.11,
        "numberOfVotes": 0
    }

Could someone help me identify where I might be going wrong as this issue should not be happening at all?
UPDATE
Company class:

export class Company {
    Id: number;
    CompanyName: string;
    CompanyDescription: string;
    Rating: number;
    CompanyValuation: number;
    Salary: number;
    ProfessionalGrowth: number;
    CompanyBenefits: number;
    CommunicationWithColleagues: number;
    EducationSector: number;
  }

data$ method:

export class CompaniesComponent implements OnInit {

  displayedColumns: string[] = ['id'];//, 'companyName'];

  data$: Observable<Company[]>;
  isLoadingResults = true;


  constructor(private api: ApiService) { }

  ngOnInit() {

    this.data$ = this.api.getAllCompanies();
    console.log(this.data$);
  }

}

and html:

 <table mat-table #table [dataSource]="data$" class="example-table"
           matSort matSortActive="id" matSortDisableClear matSortDirection="asc">

Answer №1

When updating data in the data array for Angular material, remember to call renderRows() to notify the table of changes.

To ensure that the table reflects any additions, removals, or moves in the data array, use the renderRows() function. This will update the table with the differences since the last render. If the reference to the data array is changed, the table will automatically update the rows.

The array method

To handle this, you can import MatTable and obtain a reference to it.

import {MatTable} from '@angular/material';

Use ViewChild to get the table reference.

@ViewChild(MatTable) tableReference: MatTable<Company>;

constructor(...) {}

this.api.getAllCompanies().subscribe(res => {
  this.data = res;
  this.tableReference.renderRows();
}

Add the #table reference to the table tag like <table mat-table #table>. Additionally, ensure that either the observable completes or that you unsubscribe from it.

The observable approach

An alternate method is to pass in a dataSource object or an observable instead of the array.

If providing an Observable stream, the table will automatically update when the stream emits a new data array.

data$: Observable<Company[]>;

ngOnInit() {
  this.data$ = this.api.getAllCompanies().pipe(
    finalize(() => {
      this.isLoadingResults = false;
    })
  );
}

In the template, include the $.

<table mat-table [dataSource]="data$" ...>

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

Angular 9: Subscribing triggering refreshing of the page

I've been working on an Angular 9 app that interacts with the Google Books API through requests. The issue I'm facing is that whenever the requestBookByISBN(isbn: string) function makes a .subscribe call, it triggers a page refresh which I' ...

Angular 7 application encountering error 500 with URL Rewrite Module on IIS7 server

I am facing an issue with my Angular 7 application hosted on IIS 7. The app should be accessible at https://example.com/fitcbooks/web. It was working fine initially, but suddenly stopped without any clear reason. Despite the fact that URL Rewrite on the se ...

Resharper griping about TypeScript object in Angular 2

Currently, I have Resharper 10 integrated into Visual Studio 2015. https://i.stack.imgur.com/vksGb.png In the screenshot, highlighted by the green box, there's an issue with valid decorator syntax which results in this error message: Cannot conve ...

Attempting to launch an Angular web application on Azure's Linux-based Web App service

Currently, I am in the process of deploying my angular web app onto a free tier azure web app service for testing purposes. The deployment itself is done using an Azure pipeline and seems to be successful according to the logs found in the Deployment Cente ...

flushMicrotasks does not function properly in conjunction with the image.onload event

Working on an Angular project, I'm currently developing an object with an image field. The method responsible for loading the image returns a promise that resolves in the onload function of the image. When trying to test this method using the flushMi ...

The pipe property cannot be accessed for the specified type "OperatorFunction<unknown, [unknown, boolean, any]>"

I have set up a data subscription that I want to utilize through piping, but for some reason it's not working as expected. The error message I'm receiving is: The property pipe is not available for type "OperatorFunction<unknown, [unknown, b ...

Leveraging ArangoJS Driver within an Angular2 web platform

Currently, I am in the process of working on a project that involves Angular2 and Typescript (v1.8.10). Our aim is to incorporate data from an ArangoDB database into the web application. Ideally, I would like to utilize the arangojs driver for this task. H ...

Increase the timestamp in Typescript by one hour

Is there a way to extend a timestamp by 1 hour? For instance, 1574620200000 (Including Microseconds) This is my date in timestamp format. How can I add a value to the timestamp to increase the time by an additional hour? ...

"Strategically Leveraging Nested Subscriptions in Conditional Logic

In my CRUD angular 5.5 component, I utilize routing parameters to set up its different modes (new, edit, view). I am looking for a way to avoid nested subscriptions but struggle with implementing basic conditional logic. this.route.params.subscribe((p ...

I am currently attempting to create a JavaScript function that searches for the <td> elements within an HTML table. However, the function fails to work properly when there are <th></th> tags included

UPDATE: Scratch that, I managed to solve my issue by creating a separate table for the header to contain all of my <th> tags I am working with an HTML table and I would like to add a search bar to filter through the content since it is quite large. ...

What could be causing the inner array typescript to be inaccessible in an Angular 5 application?

Below are the JSON definitions that I am working with: export class Company { name: string; trips : Trip[] = []; } export class Trip{ id: number; name: string; } Within the component, there is a method that contains the ...

Angular is receiving HTML content instead of JSON from the response of the Django server

Here's the scenario: I'm running my Angular 8 code which involves making an HTTP GET request using ng serve while also running a Django Rest Service. return Response({"product":["mac","alienware"]}) (or) return JsonResponse({"product":["mac"," ...

Overriding Bootstrap Modals with PhaserJS Canvas

I am currently working on a simple game using phaserJs with Angular and styling it with bootstrap. The issue I'm facing is that when I display a bootstrap modal and interact with it, it affects the buttons on my phaserJS canvas. Here is an example pr ...

Can the data cells of columns be dynamically adjusted to align them on a single vertical line?

For some time now, I have been grappling with a CSS issue. I am working with a table that has 3 columns displaying departures, times, and situational text for scenarios like delays or cancellations. However, as evident from the images, the alignment of th ...

Leverage jsencrypt in Ionic 3

Struggling to hash passwords for login on my Ionic 3 app, I attempted using jsencrypt following a tutorial but encountered issues as I couldn't grasp how it works... Here's what I tried : npm install --save jsencrypt import { Component } from ...

Steps for updating the clientId and authority values in MSAL configuration after they have already been read

Currently, I am utilizing Azure AD B2C for a multi-tenant application. The user starts by inputting their email, followed by selecting an option from a drop-down list populated based on the tenant they are associated with (tenant1, tenant2, tenant3). If th ...

Update to Material-UI 4.8.1 - Is there a different method for defining the `component` property now?

Note: Please note that there was a bug in version 4.8.x which caused this issue. To resolve it, make sure to upgrade to version 4.9.0 or above. In the initial version 4.8.0, the following code would compile and run smoothly: <DialogContent> {/* us ...

The function purported by WEBPACK_MODULE_13___default(...) does not exist

Scenario : I've been working on a small library (let's call it myLibrary) using TypeScript and Webpack. Everything seemed to be running smoothly until I imported the library into a React application, which resulted in a crash. On the Library Sid ...

The Angular service retrieves only the default values

I'm currently following an Angular tutorial and encountering some issues. Problem #1: The problem arises when using two services, recipe.service.ts (handles local data manipulation) and data-storage.service.ts (stores data in Firebase). When the getR ...

Instructions on how to link a button to display and conceal content when clicked

I'm working on a project with a list of headers and paragraphs, and I want to create a button that will show or hide the paragraph when clicked. However, I'm struggling with getting the paragraph to hide again when the button is clicked a second ...