Table arranged by column orientation

I am facing a unique scenario where the backend data I receive is organized in a column-oriented format. Here is an example of how the data structure looks:

[
    { columnName: "ID", cells: [1, 2, 3, 4, 5] },
    { columnName: "Name", cells: ["a", "b", "c", "d", "e"] }
]

Currently, I have configured my mat-table in the following way:

<table mat-table [dataSource]="data" class="mat-elevation-z8">
    <ng-container [matColumnDef]="column" *ngFor="let column of displayedColumns">
        <th mat-header-cell *matHeaderCellDef> {{column}} </th>
        <td mat-cell *matCellDef="let element">{{element | json}}</td>
    </ng-container>

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

This setup results in the current display:

https://i.sstatic.net/0tVon.png

However, I am aiming for a table layout like this:

|------|------|
|  ID  | NAME |
|------|------|
|   1  |   a  |
|   2  |   b  |
|   3  |   c  |
|   4  |   d  |
|   5  |   e  |

Is there a way to adjust the matRowDef so that it interprets the cells property as rows? Ideally, I would prefer making this adjustment within the mat-table without altering my data and having to convert it back later on.

Answer №1

If you need to customize the existing response, you can try making changes accordingly:

HTML Snippet:

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

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

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

Typescript Code:

import { Component } from '@angular/core';

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

const TABLE_DATA: any[] = [
  { heading: "Number", cells: [1, 2, 3, 4, 5] },
  { heading: "Letter", cells: ["a", "b", "c", "d", "e"] }
];

/**
 * @title An example demonstrating the use of `<table mat-table>`
 */
@Component({
  selector: 'table-basic-example',
  styleUrls: ['table-basic-example.css'],
  templateUrl: 'table-basic-example.html',
})
export class TableBasicExample {
  displayedColumns = [];
  dataSource = new MatTableDataSource([]);

  constructor() {
    // Get the column headings dynamically
    TABLE_DATA.forEach(item => {
      this.displayedColumns.push(item.heading);
    })

    // Customize the array for display purposes
    let modifiedArray = TABLE_DATA.reduce((array, { heading, cells }) => {
      cells.forEach((cell, index) => {
        array[index] = Object.assign({ [heading]: cell }, array[index]);
      })
      return array;
    }, [])
    this.dataSource = new MatTableDataSource(modifiedArray);
  }
}

Link to StackBlitz

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

Show the quantity of chosen selections utilizing ng-select

I have implemented the ng-select component for users to select multiple options from a list. My goal is to have the selected option displayed normally when only 1 option is chosen. However, if 2 or more options are selected, I want a custom template to sh ...

I am unsure why it is displaying these errors

I created an auto-fill form that populates data based on ng-select information automatically. However, I am encountering an issue when attempting to delete selected data as it is throwing a Cannot read property 'pincode' of null error. Any help i ...

Is it possible for Typescript to allow extracted interfaces while excluding properties from another interface?

I've been searching for information on the specific features of this. Despite my efforts on Google, I have been unable to find the details. Any help would be greatly appreciated! interface Numbers { number: number; number2: number; number ...

Developing a custom pipe in Angular4

Can anyone explain why the code snippet below has (limit) in parentheses? import { Pipe, PipeTransform } from '@angular/core' @Pipe ({ name: 'summary' }) export class SummaryPipe implements PipeTransofm { transform(value: string, l ...

Angular 17 Pokedex Encyclopedia

Recently, I tackled a challenge during my Boot Camp where I had to create a Pokedex using pokeapi. After successfully completing the challenge, I decided to refine some aspects of it. However, I encountered an unusual issue when delving into the details of ...

Steps for making a GET request from an API in Angular 7

Currently, I am attempting to retrieve JSON data using HttpClient in Angular 7. The code is functioning properly, but I am exploring the option of fetching the data directly from the API URL instead of relying on the const IMAGES array. import { Injectable ...

activating serverless.yml for aws-xray

I have been attempting to implement AWS X-Ray for all lambda functions in the following manner: serverless.yml provider: tracing: lambda: true apiGateway: true name: aws runtime: nodejs8.10 stage: ${opt:stage, 'dev'} region: ...

What is the best way to eliminate existing double quotation marks within string values stored in objects in Angular?

When using Angular, data is retrieved in object form from the database to the backend and then to the frontend. Here's how it looks in HTML: <h3>Payslip for the month of {{dataout[0].MonthYear | json }}</h3> The issue arises when running ...

FormArray in Angular2 can be nested inside another FormArray

I have the following code snippet: this.MainForm = this.fb.group({ MainArray: this.fb.array([ { ChildArray1: this.fb.array([]), ChildArray2: this.fb.array([]), } ]), }) Next, in my method, I have the following code: let MainArr ...

Dealing with router parameters of an indefinite number in Angular 5: A comprehensive guide

Is there a method to efficiently handle an unknown number of router parameters in a recursive manner? For instance: We are dealing with product categories that may have subcategories, which can have their own subcategories and so on. There are a few key ...

"Incorporating the node_modules folder into the Express.js compilation process

Is there a way to automatically include dependencies during Express.js compilation, similar to building a React project? I want to avoid dealing with dependencies after the build process. Any suggestions on how to achieve this? I have not attempted any so ...

Guidelines for importing dependencies of nested components in Angular 6

I am currently in the process of creating two components: Configuracion and Equipo. The setup for these components is located in configuracion.component.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular ...

Issue with Navigating Angular Buttons

In my Angular application, I have a mat-card component containing a list of buttons. Below is the code snippet: <mat-card class="side-card"> <mat-card-title>Images</mat-card-title> <mat-card-subtitle>Choose to star ...

Display content from Angular 5 template directly in table without using parent template

Despite the fact that this question has been raised multiple times, I find myself in a slightly tricky situation. Here is the structure of my table: <table> <th>...</th> <app-custom-rows *ngFor="let t..." [customAttribute]="someval ...

Demonstrating reactivity: updating an array property based on a window event

One example scenario involves setting specific elements to have an active class by assigning the property "active" as true (using v-bind:class). This property is modified within a foreach loop, after certain conditions are met, through the method "handleSc ...

Managing Import Structure in Turborepo/Typescript Package

I am currently working on creating a range of TypeScript packages as part of a Turborepo project. Here is an example of how the import structure for these packages looks like: import { Test } from "package-name" import { Test } from "package ...

Visual Studio encountering an error with AngularJS TypeScript integration

Hey everyone! I recently installed the angularjs.typescript and jquery.typescript packages from NuGet. However, I'm encountering errors in Visual Studio, as shown in the attached image. I'm using VS 2013 U4 and have updated all extensions and p ...

What is the process for removing an item from a JSON file using an HTTP DELETE request in a Node.js environment?

Essentially, I have a JSON file containing user and group data and I need to delete a specific group from it. Below is a snippet of the JSON file named authdata.json: [{ "name": "Allan", "role": ["Group Admin", "Super Admin"], "group": ["Cool- ...

Developing a Typescript npm package

In my project, there is a directory called models (named my-models) which houses several important typescript classes for my application. While I have been able to use these classes within the app without any issues, I now wish to turn it into an npm pack ...

Utilizing custom colors in a Typescript/React/MUI Button component to enhance its design

How can I apply custom colors to the Button component without getting an error? Are there any possible solutions for this issue? I followed the module augmentation approach outlined in the documentation, but the problem persists: https://mui.com/material ...