Angular Material table source data not rendering properly

I have successfully displayed dataSource2 (example from Angular library) but I am facing issues rendering my own dataSource variable.

Despite making both data sources similar and using the Angular Material library in a consistent manner, I cannot figure out why my dataSource is not being rendered properly. Could it be an issue with how the Material library functions?

View the image showing the message on dataSource not being rendered

My TypeScript (.ts) file:

import { Component, OnInit, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { BackendcallingService } from './../backendcalling.service';
import { AvailableRolesEntity, RoleFunctionsEntity, ChildRolesEntity } from 'src/models/AvailableRoles.model';
import { MatTableDataSource } from '@angular/material';

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

  jsondata: any;
  jsonifiedrole: any;
  availableRoles: any;
  jsonifiedavailableRoles: any[];

  dataSource: any = [];
  dataSource2: any =[];

  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol']; // Columns for example dataSource2
  columnsToDisplay = ['name', 'priority', 'editUrl', 'active', 'createdId']; // Columns for my dataSource

  ELEMENT_DATA: any[] = [
    { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
    { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
    { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
    { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
  ];

  svc: any;
  http: any;

  response: any;

  constructor(http: HttpClient, svc: BackendcallingService) {
    this.http = http;
    this.svc = svc;
  }

  ngOnInit() {
    this.http.get('http://localhost:8080/epsdk-app-os/get_role?role_id=undefined')
      .subscribe(response => {
        this.response = response;
        this.jsondata = JSON.parse(response.data);
        this.role = this.jsondata.role;
        this.jsonifiedrole = JSON.parse(this.role);

        this.availableRoles = this.jsondata.availableRoles;
        this.jsonifiedavailableRoles = JSON.parse(this.availableRoles);

        this.dataSource2 = new MatTableDataSource<any>(this.ELEMENT_DATA); // Example data source
        this.dataSource = new MatTableDataSource<any>(this.jsonifiedavailableRoles); // My datasource

        console.log(this.jsondata);
        console.log(this.role);
        console.log(this.jsonifiedrole);
        console.log(this.availableRoles);
        console.log(this.jsonifiedavailableRoles);
      });
  }
}

The jsonifiedavailableRoles array structure might differ from ELEMENT_DATA which renders correctly as dataSource2.

Check out the image displaying how jsonifiedavailableRoles looks like

My HTML file:

<div>
  <table mat-table [dataSource]="dataSource2" class="mat-elevation-z8">
    <ng-container matColumnDef="position">
      <th mat-header-cell *matHeaderCellDef> No. </th>
      <td mat-cell *matCellDef="let element"> {{element.position}} </td>
    </ng-container>

    <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="weight">
      <th mat-header-cell *matHeaderCellDef> Weight </th>
      <td mat-cell *matCellDef="let element"> {{element.weight}} </td>
    </ng-container>

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

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

<div>
  <br>
  <table mat-table [dataSource]="dataSource">

    <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="priority">
      <th mat-header-cell *matHeaderCellDef> Priority </th>
      <td mat-cell *matCellDef="let element"> {{element.priority}} </td>
    </ng-container>

    ...
  
    <tr mat-header-row *matHeaderRowDef="columnsToDisplay"></tr>
    <tr mat-row *matRowDef="let row; columns: columnsToDisplay;"></tr>
  </table>
</div>

Answer №1

columnsToDisplay needs to be aligned with the HTML structure in your code.

columnsToDisplay = ['title', 'category', 'url', 'status', 'authorId'];  // define columns for dataSource

<td mat-cell *matCellDef="let item"> {{item.title}} </td>

Answer №2

Make sure to update the HTML code as follows:

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

Don't forget to include this.jsonifiedavailableRoles in your get() method within ngOnInit.

this.dataSource = new MatTableDataSource<any>(this.jsonifiedavailableRoles);

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

Mapping Firebase UserInfo to a custom User model in Angular 7 using Angular Fire

I am a beginner with angular 7, and I am attempting to retrieve the current authenticated user from Firebase and map it to my custom User model (without using a constructor in User). The Firebase API structure: interface UserInfo { displayName: string ...

Verify the status of the mongodb server synchronously

Is there a method to detect if a mongod instance is still operational while using mongoclient? In my mongoclient module, I have implemented a db.on('close') handler which functions properly when mongod exits normally. However, if the server proc ...

Retrieve the data from all checkboxes using JavaScript

Whenever the button is clicked, a new category is added to the database and displayed on the same page. However, an issue arises when multiple clicks on the button result in multiple checkboxes being added with the same value. I have implemented a check to ...

The mathematical logic behind navigating forward and backward in Angular

Calling all math experts! I need your help with a slider issue. The prevSlide function is working perfectly, but the nextSlide function seems to be starting off on the wrong foot. It goes 1-2-3 and then jumps to 2-3-2-3... It's definitely a math probl ...

The Raycaster fails to identify objects that have been rotated

I have recently started working with Three.js and I'm facing an issue with raycasting not detecting certain parts of a rotated mesh object. For instance, in the image below, when the mouse is at the position of the green circle, it's detected as ...

Press on a list item within Angular Material 2/4

My goal is to trigger a function when clicking on any row of a list or table. I have not been able to achieve this, so now I am attempting to have the function called when clicking on the first column of each row. The structure of my component.html, which ...

What is the most efficient way to create multiple nested property objects in a shorter amount of time?

Currently, I am utilizing mongoDB for a data migration project where queries are written in plain JavaScript/JSON format: queryObj = {}; // main object passed to mongodb for queries The code snippet below is causing an error: queryObj[inObj.row]['$ ...

Can one select a radio button without corrupting the data in VUE?

How can I preselect a value for radio buttons created using Vue's List Rendering without having a dataset in the script? Below is the code snippet for a better understanding of my goal: SCRIPT: data() { return { formData: {} //formData st ...

Enhance Your GoJS Pipeline Visualization with TextBlocks

I am facing challenges in customizing the GoJS Pipes example to include text within the "pipes" without disrupting the layout. Although I referred to an older response on the same query here, it seems outdated or not detailed enough for me to implement wit ...

The 'version' property is not found in the type 'Request<ParamsDictionary, any, any, ParsedQs>'

Here is the code snippet that I am currently using: app.use(function (req: Request, res, next) { req.version = req.headers['accept-version'] || '1.0.0'; next(); }); In addition, I have a file named express.d.ts declare namespace Ex ...

Transmit an array in JavaScript to a fresh window by utilizing the window.open function

Is it possible to pass an array from the current page to a new page opened using the window.open function? If so, how can this be accomplished? ...

How can we make quotes in text SQL-friendly by doubling them up?

When inserting text into an SQL query that contains quotes (for example: I'm --text---), the single quote in I'm must be escaped by doubling it up to prevent server crashes. How can this be achieved using JavaScript? Is there an NPM package avai ...

Obtaining a complex object from a Checkbox set in AngularJS through the use of ngModel

Hey there! I've been searching on Stack Overflow regarding this topic, but I haven't found a solution that matches exactly what I need. If you want to take a look at the code, here is a JSFiddle link for reference: http://jsfiddle.net/gsLXf/1/ ...

How to implement the connect function in an Angular 2 table

Topic: Angular Material 2 implementation of md-table UI using cdk-table Problem: Unable to trigger connect method after a user-initiated HTTP call receives a response Approach: Create a hot observable from a behavior subject in a service. The parent c ...

Leveraging the Three.js STL loader in the Angular framework

Having trouble loading a simple stl file onto a canvas in an Angular project. I've followed several guides with no success, although it works fine when using native JavaScript. The HTML includes a canvas with a ViewChild: <canvas #myCanvas>< ...

Creating a dynamic text expansion feature triggered by the mouse hovering over

I am looking to create an expanding menu text similar to what can be found on this webpage: example Below is my JavaScript code that currently works but has some drawbacks. The code is lengthy, not very professional, and lacks responsiveness. For instance ...

Transfer data to clipboard

Is there a way to copy information via href to the clipboard? I'm looking to achieve something like this; <?php print "Number: <a href=\"" . $number . ">" . $number . "</a>"; ?> When someone clicks the link, the information ...

What's the best method to call a PHP file using AJAX/JavaScript?

I am having an issue with my code that uses AJAX to GET a PHP file. The main objective is to notify the user whether the movie table is empty or not. If the table turns out to be empty, a confirmation box will pop up asking the user if they want to add mov ...

Working with multiple observables in an array of properties using RXJS

I'm relatively new to using rxjs in my angular projects and I'm facing a challenge with a simple scenario. When making an http call to retrieve a group, it returns data including a list of "buddy ids", "genre ids", and a "region id". In order t ...

Angular HTTP Patch method requires explicitly defined HTTP options as input parameters

I encountered a challenge with using Angular's HTTP patch method and noticed that the overloaded function patch(url, body, options) only accepts hardcoded values for HTTP options. An example of a hardcoded approach that works: patchEntity(id: number) ...