Utilizing Angular Material Table to present information efficiently

I have a unique data structure that I need to present using mat-table.

dataSource= [[1,2],[3,4],[5,6]]

In this structure, dataSource[0] always serves as the heading, with the rest of the array items representing its rows.

Therefore, the expected output for the above data should be as follows:

1 2 Table Heading

3 4

5 6

Is it possible to achieve the above data structure using mat-table? Any assistance is appreciated.

Note: I have reviewed the mat-table documentation but haven't found anything that addresses my specific needs.

Answer №1

To accomplish this task, you must first extract the column names' values and separate them from the actual data.

export class TableBasicExample {
  data = [[1,2],[3,4],[5,6]];
  dataSource = this.data.splice(1);
  displayedColumns: string[] = this.data[0].map(value => String(value));
}

You can dynamically bind these dataSource and column names in your template.

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

    <!--- Note that these columns can be defined in any order.
        The actual rendered columns are set as a property on the row definition" -->

    <!-- Position Column -->
    <ng-container matColumnDef="{{displayedColumns[0]}}">
        <th mat-header-cell *matHeaderCellDef> {{displayedColumns[0]}} </th>
        <td mat-cell *matCellDef="let element"> {{element[0]}} </td>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="{{displayedColumns[1]}}">
        <th mat-header-cell *matHeaderCellDef> {{displayedColumns[1]}} </th>
        <td mat-cell *matCellDef="let element"> {{element[1]}} </td>
    </ng-container>

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

You can view the functional stackblitz example here: https://stackblitz.com/edit/angular-nmnymd

Answer №2

If you want to create a dynamic table based on your data, follow these steps:

In the component.ts file:

public data: any[] = [['age', 'height'], [3, 4], [5, 6]]
  public dataSource: any[] = [];
  displayedColumns: string[] = [];
  isDataReady: boolean = false;

  constructor() {
    this.displayedColumns = this.data[0];
    let tempArr = this.data.slice(1, this.data.length);
    tempArr.forEach((el: any[]) => {
      let obj: any = {};
      el.forEach((key, i) => {
        obj[this.displayedColumns[i]] = key;
      });
      this.dataSource.push(obj);
    });
  }

Then, in the component.html, create the table columns like this:

<ng-container *ngFor="let col of displayedColumns" [matColumnDef]="col">
    <th mat-header-cell *matHeaderCellDef> {{col}} </th>
    <td mat-cell *matCellDef="let element"> {{element[col]}} </td>
  </ng-container>

Check out the working example demo

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

In Ionic 2, trying to access the IONIC_ENV variable consistently results in it being undefined

Does anyone know how to access the IONIC_ENV variable in order to switch between using the API URL for production and development environments? Every time I try to check it, it returns undefined. process.env.IONIC_ENV I might need to run or add another c ...

Looking for guidance on implementing explicit waits in Protractor for non-angular applications

I have noticed that automating non-angular applications with Protractor can be challenging. Currently, I am using some methods to add an explicit wait to my existing Serenity click and enter functions. However, I am curious if there is a way to automatic ...

The status property in Angular 4 is currently not defined or is referencing a null value

I am currently working with angular 4 and ionic 3, and encountering an error message that says unable to get property 'status' undefined or null reference from the JSON data I am displaying on my HTML page. Here is a snippet of my home.ts file: ...

Issue: Encountering an ObjectUnsubscribedError while using Observables in RxJS and Angular2

Currently, I am in the process of self-teaching Angular2 and realize that I need to find better resources. One issue I am facing is related to moving my data calls to a service and utilizing Reactive Subject & BehaviorSubject as recommended by a friend. Wh ...

How to use multiple template urls in Angular 6

Currently, I am creating a front-end using Angular 6 and facing the challenge of having components with varying html structures based on the user who is logged in. The number of templates required can range from 2 to over 20, so my preference would be to ...

The Javascript Node class encountered an error: X has not been defined

I have a class that looks like this: const MongoClient = require("mongodb").MongoClient; const ConnectionDetails = require("./ConnectionDetails").ConnectionDetails; const Recipe = require("./recipe").Recipe; var ObjectId = req ...

What is the best way to dynamically add fields to every object in an array of Firestore documents using RxJS?

Trying to solve a challenging RxJS issue here. In my Angular service class, I initially had a method that fetched data from the Firebase Firestore database like this: async getAllEmployees() { return <Observable<User[]>> this.firestore.co ...

Tips for transferring observable to parent component in angular 2?

I have two components, SearchComponent and RuleListComponent. The Search component is a child of RuleList. https://i.stack.imgur.com/rFlM2.png I need the SearchComponent to retrieve data using APIService. This data should then be passed to RuleList as an ...

Prevent Ionic 2 hardware back button from triggering default action

Is there a way to prevent the default navigation when tapping the hardware back button? I attempted using registerBackButtonAction, but it ends up overriding the behavior of the back button on every page, which is not desired. I also tried this method: d ...

How are the .map files utilized in angular-cli, and is there a way for ng build to generate these files automatically?

When running ng build with angular-cli, it generates three files: inline.bundle.js vendor.bundle.js main.bundle.js In addition, it also creates a map file for each one. But why? I am wondering if there is a way to customize this process and avoid genera ...

Angular 8: ngx-socket-io changes the connection URL while in production mode

One issue arises when running the application in production mode. In development mode, the socket client successfully connects to http://localhost:3002/socket.io/?EIO=3&transport=polling&t=N4--_Ms. However, in production mode, the URL changes to ht ...

NPM is lacking in providing sufficient guidance on resolving dependency problems

While attempting to incorporate Typescript into my Gatsby project after the fact, I encountered a cryptic error from NPM: npm ERR! code EOVERRIDE npm ERR! Override for @types/react@* conflicts with direct dependency npm ERR! A complete log of this run can ...

Utilizing environment variables in the root files of your SvelteKit project: A guide

I have encountered an issue with my SvelteKit project which uses TypeScript and includes a .env file at the root. Additionally, I have added a drizzle.config.ts file at the root directory. The problem arises when I try to import DATABASE_HOST from $env/sta ...

Type to match the data type of the enum, not strictly one specific value

enum X { A = 'x', B = 'y' } type A<T> = { prop1: T prop2: X } let r:A<X> = { prop1: X.A, prop2: X } What specific type must be assigned to A.prop2 in order for only X and no other item to also be assigned to i ...

You cannot access the property 'subscribe' on a void type in Angular 2

fetchNews(newsCategory : any){ this.storage.get("USER_INFO").then(result =>{ this.storage.get("sessionkey").then(tempSessionKey =>{ this.email = JSON.parse(result).email; this.newSessionKey = tempSessionKey; this.authKey =JSON.stringify("Basic ...

Guide on setting up an AWS code pipeline for Elastic Beanstalk deployment on ASP.NET Core 5.0 with Angular

I am facing a challenge with deploying my ASP.NET Core 5.0 application with Angular to the EBS Windows environment using AWS CodePipeline (CI / CD). Despite searching various internet resources for solutions, I have not been able to find much help. My att ...

Having trouble establishing a connection with Db2 while using protractor

Encountering an issue when attempting to establish a connection with a remote DB2 database, resulting in the following exception: SQL30081N A communication error has been detected. The communication protocol in use is 'TCP/IP'. The com ...

How to implement div scrolling on button click using Angular 4

Is there a way to make the contents of a div scroll to the left when one button is clicked and to the right when another button is clicked? I've tried using ScrollLeft, but it doesn't seem to be working... Here's the HTML code: <button ...

Using Ngrx with Angular

When I call dispatch, the data isn't being stored properly. It might be a simple mistake, but as a beginner, I'm having trouble finding it. This is my store setup - User is an interface I created in another file: import { Action } from '@ng ...

PhantomJS version 2.1.1 encountered an error on a Windows 7 system, displaying "ReferenceError: Map variable not found."

I've been utilizing the "MVC ASP.NET Core with Angular" template. I'm attempting to incorporate phantomJS and execute the tests, but encountering the following errors: ERROR in [at-loader] ..\\node_modules\zone.js\dist&bs ...