How can I populate a mat-table in Angular 7 with data stored in an object?

At the moment, my code is set up to populate a table with data.

In my component.ts file:

import { HttpClient } from "@angular/common/http";
import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import { MatTableDataSource } from "@angular/material/table";

@Component({
  styleUrls: ["./styles.scss"],
  templateUrl: "./template.html"
})
export class DisplayEmployeeData {
  employeeDataSheet: object;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http
      .get("http://localhost:5000/EmployeeData/GetData")
      .subscribe(response => {
        this.employeeDataSheet = response;
      });
  }
}

The template.html code structure is as follows:

<mat-card style="height: 98%">
  <div style="height: 95%; overflow: auto;">
      <table class="StyledTable">
        <thead>
          <tr>
            <td>Name</td>
            <td>Age</td>
            <td>Date Of Birth</td>
            <td>Address</td>
            <td>Postcode</td>
            <td>Gender</td>
            <td>Salary</td>
            <td>Job Title</td>
          </tr>
        </thead>

        <tr *ngFor="let info of employeeDataSheet">
          <td>{{info.Name}}</td>
          <td>{{info.Age}}</td>
          <td>{{info.DateOfBirth}}</td>
          <td>{{info.Address}}</td>
          <td>{{info.Postcode}}</td>
          <td>{{info.Gender}}</td>
          <td>{{info.Salary}}</td>
          <td>{{info.JobTitle}}</td>
      </table>
    </div>

</mat-card>

Although functional, I find the appearance unattractive. My goal is to implement a mat-table according to https://material.angular.io/components/table/examples

I have made changes in the template.html as follows:

<mat-card style="height: 98%">
    <table mat-table [dataSource]="employeeDataSheet" class="mat-elevation-z8">
        <ng-container matColumnDef="Name">
            <th mat-header-cell *matHeaderCellDef>Name </th>
            <td mat-cell *matCellDef="let element"> {{element.Name}} </td>
        </ng-container>
        <ng-container matColumnDef="DateOfBirth">
            <th mat-header-cell *matHeaderCellDef> DateOfBirth </th>
            <td mat-cell *matCellDef="let element"> {{element.DateOfBirth}} </td>
        </ng-container>
        <ng-container matColumnDef="Address">
            <th mat-header-cell *matHeaderCellDef> Address </th>
            <td mat-cell *matCellDef="let element"> {{element.Address}} </td>
        </ng-container>
        <ng-container matColumnDef="Postcode">
            <th mat-header-cell *matHeaderCellDef> Postcode </th>
            <td mat-cell *matCellDef="let element"> {{element.Postcode}} </td>

        <ng-container matColumnDef="Gender">
            <th mat-header-cell *matHeaderCellDef> Gender </th>
            <td mat-cell *matCellDef="let element"> {{element.Gender}} </td>
        </ng-container>
        <ng-container matColumnDef="Salary">
            <th mat-header-cell *matHeaderCellDef> Salary </th>
            <td mat-cell *matCellDef="let element"> {{element.Salary}} </td>
        </ng-container>
        <ng-container matColumnDef="JobTitle">
            <th mat-header-cell *matHeaderCellDef> JobTitle </th>
            <td mat-cell *matCellDef="let element"> {{element.JobTitle}} </td>
        </ng-container>

        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
    </table>
</mat-card>

However, upon running this updated code, the screen remains blank without any error messages. What amendments should be made in the template.html and/or component.ts to display the data correctly?

Answer №1

Make the following modifications:

In component.ts:

import { HttpClient } from "@angular/common/http";
import { Component, OnInit } from "@angular/core";
import { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import { MatTableDataSource } from "@angular/material";
import { MyObject} from "../my-object.model";

@Component({
   styleUrls: ["./styles.scss"],
   templateUrl: "./template.html"
})
export class MyRouteData implements OnInit {
   employeeInfoTable : MyObject[] = [];
   employeeInfoTableDataSource = new MatTableDataSource(this.employeeInfoTable);
   displayedColumns: string[] = [
     "Name",
     "DateOfBirth",
     "Address",
     "Postcode",
     "Gender",
     "Salary"
     "JobTitle"
  ];

   constructor(private http: HttpClient) {}

   ngOnInit() {
      this.http.get("http://localhost:5000/MyRoute/GetEmployeeInfo")
          .subscribe(response => {
             this.employeeInfoTable = response;
             this.employeeInfoTableDataSource.data = this.employeeInfoTable;
      });
   }
}

In my-object.model.ts

export interface MyObject{
   id: number;
   Name: string;
   DateOfBirth: Date;
   Address: string;
   Postcode: string;
   Gender: string;
   Salary : number;
   JobTitle : string;
}

In your .html

<mat-card style="height: 98%">
  <table mat-table [dataSource]="employeeInfoTableDataSource" class="mat-elevation-z8">
    <ng-container matColumnDef="Name">
        <th mat-header-cell *matHeaderCellDef>Name </th>
        <td mat-cell *matCellDef="let element"> {{element.Name}} </td>
    </ng-container>
    <ng-container matColumnDef="DateOfBirth">
        <th mat-header-cell *matHeaderCellDef> DateOfBirth </th>
        <td mat-cell *matCellDef="let element"> {{element.DateOfBirth}} </td>
    </ng-container>
    <ng-container matColumnDef="Address">
        <th mat-header-cell *matHeaderCellDef> Address </th>
        <td mat-cell *matCellDef="let element"> {{element.Address}} </td>
    </ng-container>
    <ng-container matColumnDef="Postcode">
        <th mat-header-cell *matHeaderCellDef> Postcode </th>
        <td mat-cell *matCellDef="let element"> {{element.Postcode}} </td>

    <ng-container matColumnDef="Gender">
        <th mat-header-cell *matHeaderCellDef> Gender </th>
        <td mat-cell *matCellDef="let element"> {{element.Gender}} </td>
    </ng-container>
    <ng-container matColumnDef="Salary">
        <th mat-header-cell *matHeaderCellDef> Salary </th>
        <td mat-cell *matCellDef="let element"> {{element.Salary}} </td>
    </ng-container>
    <ng-container matColumnDef="JobTitle">
        <th mat-header-cell *matHeaderCellDef> JobTitle </th>
        <td mat-cell *matCellDef="let element"> {{element.JobTitle}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</mat-card>

Answer №2

To enhance the functionality of your Component.ts file, you should implement 2 key modifications:

1) Define the 'displayedColumns' property. (It's worth noting that having 2 'Postcode' columns in your table is not permitted. I have removed one instance from the displayedColumns definition and recommend removing it from your HTML table as well).

public displayedColumns = ['Name', 'DateOfBirth', 'address', 'Postcode', 'Gender', 'Salary', 'JobTitle', 'inbound', 'ping_time'];

2) Set the response data to employeeInfoTable as a MatTableDataSource type. This assignment will be essential for handling individual rows effectively.

public employeeInfoTable: any;
this.employeeInfoTable = new MatTableDataSource<any>([...response]);;

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

Having difficulty selecting an item from the MaterialUI package

While trying to utilize the MaterialUI Select component with typescript/reactjs, I encountered an issue during the instantiation of the Select element. The error message I'm receiving states: Type 'Courses' is missing the following properti ...

The functionality of MaterializeCSS modals seems to be experiencing issues within an Angular2 (webpack) application

My goal is to display modals with a modal-trigger without it automatically popping up during application initialization. However, every time I start my application, the modal pops up instantly. Below is the code snippet from my component .ts file: import ...

Upon attempting to open Google Maps for the second time, an error message pops up indicating that the Google Maps JavaScript API has been included multiple times on this page

Currently, I am utilizing the npm package known as google-maps and integrating it with an angular material modal to display a map. However, upon opening the map for the second time, an error message is triggered: You have included the Google Maps JavaScri ...

Implementing Angular *ngFor to Reference an Object Using Its Key

myjson is a collection of various hijabs and headscarves: [ { "support": 2, "items": [ [ { "title": "Segitiga Wolfis", "price": 23000, "descripti ...

What is the best way to save an array of values in a MySQL table?

When values are submitted via a form, they are stored in the array. $array= array("123","James","New York"); The MySQL table(Customer) ID-----NAME-----CITY Having recently started learning PHP, I am interested in inserting the array data into the relev ...

What is the proper way to add a string to a TypeScript array?

When attempting to add a string to a TypeScript array, I am encountering an error stating 'cannot push to undefined'. Is this the correct approach, or should I be using the spread operator instead? api.ts const api: IConfigName = {name: "getKey ...

Struggling with setting up Angular Material and SCSS configuration in my application -

Hey there, I encountered an error or warning while trying to launch my angular app. Here's the issue: ERROR in ./src/styles/styles.scss (./node_modules/@angular-devkit/build- angular/src/angular-cli-files/plugins/raw-css- loader.js!./n ...

Ways to modify the information retrieved from JSON?

I've integrated the OMDB api (Online Movie DB) into my project. The interface I created is returning the expected data types, with data being returned as {Search: Array(10), totalResults: "31", Response: "True"} when using the http get method. The spe ...

Verify the presence of identical items in the array

I have been attempting to identify any duplicate values within an array of objects and create a function in ES6 that will return true if duplicates are found. arrayOne = [{ agrregatedVal: "count", value: "Employee Full Name" }, { agrrega ...

Troubleshooting: Issues with accessing Angular/Typescript Class Getter property

I have a class defined as follows: export class Story { id: number; title: string; storyText: string; utcDate: string; get displayDate(): string { const today = new Date(); const postDate = new Date(this.utcDate); ...

Tips for using useState to update only the element that was clicked:

When I click the button to add a step to a chapter, it's adding a step to all chapters instead of just one. What mistake am I making? const example_chapters = [ { id: 1, title: 'Chapter 1'}, { id: 2, title: 'Chapter 2'}, ...

Unable to modify translation values in an existing ngx-translate object

I am facing an issue where I am unable to change the value of an object property within a translation JSON file using ngx translate. Despite attempting to update the value dynamically when receiving data from an API, it seems to remain unchanged. I have t ...

Checkbox Event Restricts Access to a Single Class Variable

As a beginner in AngularJS (just diving in this week), I've encountered an issue with a checkbox input connected to an ng-change event. <input type="checkbox" ng-model="vm.hasCondoKey" ng-change="vm.onKeyCheckboxChange()" /> The ng-change even ...

Absent observable functions in the RxJS 5.0.0-beta.0 release

I am encountering an issue when trying to use RxJS with Angular 2. The methods recommended from the Typescript definition file are not present on my Observable object... https://i.stack.imgur.com/6qhS4.png https://i.stack.imgur.com/m7OBk.png After inves ...

Error: Unable to dispatch a Redux-thunk action with additional arguments in React

Currently, I am attempting to work with TypeScript alongside Redux-Thunk and Redux. My goal is to pass an object to any action (I am utilizing dependency injection and need to pass either an object service or a string). However, I encountered the followin ...

Angular 6's observable variable doesn't properly support Ng If functionality

I successfully implemented server-side pagination in the Angular6 material data grid following the instructions from this link. Now, I am facing an issue where I want to display a "No Data Found" message if the response dataset is empty. I tried using ngI ...

Arranging arrays of various types in typescript

I need help sorting parameters in my TypeScript model. Here is a snippet of my model: export class DataModel { ID: String point1: Point point2 : Point point3: Point AnotherPoint1: AnotherPoint[] AnotherPoint2: AnotherPoint[] AnotherPoi ...

Limiting the use of TypeScript ambient declarations to designated files such as those with the extension *.spec.ts

In my Jest setupTests file, I define several global identifiers such as "global.sinon = sinon". However, when typing these in ambient declarations, they apply to all files, not just the *.spec.ts files where the setupTests file is included. In the past, ...

What could be causing the undefined value in my Many-to-Many relationship field?

Currently, I am in the process of setting up a follower/following system. However, as I attempt to add a new user to the following list, I encounter an error stating Cannot read property 'push' of undefined. This issue results in the creation of ...

Unable to retrieve JSON data from php script, but able to successfully retrieve it from file.json

This is the function of my PHP testing script: $json = array ( "age" => 5, "name" => "Lee", ); $json = json_encode($json); echo $json; The JSON data is successfully printed out. When I save its content in a file named file.json and read ...