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:

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

What is the purpose of the tabindex in the MUI Modal component?

Struggling with integrating a modal into my project - it's refusing to close and taking up the entire screen height. On inspection, I found this troublesome code: [tabindex]: outline: none; height: 100% How can I remove height: 100% from the ...

What is the most efficient method for validating an exception in Protractor?

In recent code reviews within our team, a discussion arose about writing tests that assert on expected exceptions. While this is correct, the method used involved a try/catch block, which some believe may not be the most performant approach. This raises th ...

Strange occurrences observed while looping through an enum in TypeScript

Just now, I came across this issue while attempting to loop through an enum. Imagine you have the following: enum Gender { Male = 1, Female = 2 } If you write: for (let gender in Gender) { console.log(gender) } You will notice that it iter ...

Tips for creating a carousel with Angular 9 to showcase numerous items

I've got this code snippet that I'm working on. I want to incorporate a Carousel feature using Angular 9 without relying on any external libraries. Currently, all the data items are appearing in a single row (they are exceeding the specified bor ...

Looking to change the pagination arrow icons in Angular's mat-paginator to something different. Let's replace them with new icons

Looking to customize the arrows icons on an Angular mat-paginator for a unique design. For more information on mat-paginator, please see this link: https://material.angular.io/components/paginator/overview I attempted to locate a way to change the icon by ...

Angular Material's floating label feature disrupts the form field's outline styling

Whenever I try to change the appearance of the form field to outline, the floating label ends up breaking the outline. Here is a code snippet for reference: <mat-form-field appearance="outline"> <mat-label>Password&l ...

Tips for generating a list in Angular2 based on previous selections

import { Component } from '@angular/core'; export class Superhero { name: string; } const SUPERHEROES: Superhero[] = [ { name: 'GK-1' }, { name: 'GK-2' }, { name: 'GK-3' }, { name: 'GK-4&ap ...

Accessing cell values within a table using JavaScript

I am having some trouble with extracting unique IDs from the input text areas in the first column of an HTML table. These IDs are dynamically assigned using JavaScript. Can someone help me with this issue? Below is the HTML code for my table: <table id ...

Sharing content on an Angular 4/5 webpage

I find myself in a situation where I am required to share a link to my web application with a client, and they will be submitting a form on my webpage. This application has been developed using Angular 5. Despite searching online for a solution, I have not ...

Experiencing an issue when attempting to deploy Strapi CMS with TypeScript on Railway - encountering the error message: "Unable to locate module 'typescript'"

Issue with Deploying Strapi CMS in TypeScript to Railway Currently facing challenges while trying to deploy Strapi CMS written in TypeScript to Railway. Despite the availability of a JavaScript template, there's a lack of a specific TypeScript templa ...

Ways to prevent the need for explicit undefined checks when passing a string prop to a component in TypeScript

Can the checkVar function be modified to prevent the occurrence of an error message TS2322: Type string | undefined is not assignable to type string? // The TestComponent function takes a parameter fooProp that should be a string. function TestComponent({ ...

Retrieve data from an HTML form within an Angular 2 ag-grid component

I'm facing a challenge with incorporating form values from a modal into an ag-grid array in my HTML file. I'm unsure of the process to achieve this. Below is an excerpt from my file.html: <template #addTrainContent let-c="close" let-d="dismi ...

RxJS mergeMap waits for the completion of inner Observables before moving on to

I encountered an issue with my solution that initially appeared to be working, but when tested on a slow network: public getKeyFigureValuesForAllClients(keyFigurename: string) { const keyFigureDefintion$ = this.keyFigureDefintions$.pipe( flatMap ...

Generate a new Angular component by only creating the TypeScript file

As a newcomer to Angular, I recently purchased the Metronic theme. After installing all necessary components, including the latest version of angular CLI, I encountered an issue. Whenever I run the command ng generate component test, it only creates a test ...

Tips for preserving images while browsing a website built with Angular single-page application

Utilizing Angular's router for component navigation has been beneficial, but I am facing an issue with component reloads when going back. To address the problem of content reloading from the server, I have implemented a solution where the content arra ...

Adjust Column Title in Table

Is it possible to customize the column headers in a mat-table and save the updated value in a variable? I've been looking for a solution to this but haven't found one yet. ...

Svelte: highlighting input text when selected

Is there a way to select the text of an input element when it is focused using bind:this={ref} and then ref.select()? It seems to only work when I remove the bind:value from the input element. Why is that the case, and how can I solve this issue? Thank yo ...

Ways to simulate a dependent class in TypeScript & JEST without modifying constructor parameters to optional

Currently, I am attempting to replicate a well-known process in Java development using TypeScript and JEST for practice. In this scenario, there is a Controller class that relies on a Service class. The connection between the two is established through the ...

React TypeScript - creating a component with a defined interface and extra properties

I'm completely new to Typescript and I am having trouble with rendering a component and passing in an onClick function. How can I properly pass in an onClick function to the CarItem? It seems like it's treating onMenuClick as a property of ICar, ...

Modify every audio mixer for Windows

Currently working on developing software for Windows using typescript. Looking to modify the audio being played on Windows by utilizing the mixer for individual applications similar to the built-in Windows audio mixer. Came across a plugin called win-audi ...