Creating adaptable rows and columns with Angular Material's data table feature

My approach to rendering dynamic rows and columns using a basic table was successful:

<tbody>
    <tr *ngFor="let row of data">
      <td *ngFor="let val of row">
        {{ val }}
      </td>
    </tr>
  </tbody>
</table>

However, when I attempted the same logic with Angular mat-table, I encountered an error:

ERROR Error: Duplicate column definition name provided: "undefined"

<mat-table #table [dataSource]="data">
  <ng-container [matColumnDef]="col" *ngFor="let row of data">
    <mat-header-cell *matHeaderCellDef> {{ row }} </mat-header-cell>
    <mat-cell *matCellDef="let element"> {{ element[col] }} </mat-cell>
  </ng-container>
  <mat-header-row *matHeaderRowDef="data"></mat-header-row>
  <mat-row *matRowDef="let row; columns: data"></mat-row>
</mat-table>

I need guidance on this issue.

UPDATE

I am trying to display Excel data in a mat-table. While I can do it easily with a simple table, I am facing challenges with mat-table implementation.

Please take a look at the following StackBlitz for more details:

https://stackblitz.com/edit/angular-excel-read-table

Answer №1

If you're looking for a solution, the code below should be able to help:

<table mat-table [dataSource]="data">
  <ng-container *ngFor="let columnName of columnNames" [matColumnDef]="columnName">
    <th mat-header-cell *matHeaderCellDef>{{ columnName }}</th>
    <td mat-cell *matCellDef="let row">{{ row[columnName] }}</td>
  </ng-container>
  <tr mat-header-row *matHeaderRowDef="columnNames"></tr>
  <tr mat-row *matRowDef="let row; columns: columnNames"></tr>
</table>

To make this work, ensure that you have an array called columnNames defined in your component class. This array should contain the property names of the objects in your table rows.

For further guidance and testing, you can check out this 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

Every time I attempt to execute an npm command, such as ng new, I encounter a "module not found" error despite having installed node version "v16.13.0"

https://i.stack.imgur.com/RBxyI.png node:internal/modules/cjs/loader:936 throw err; ^ Error: Cannot locate module 'C:\Program Files\nodejs\node_modules\npm\bin\node_modules\npm\bin\npm-cli.js' ...

Guide to creating an Express + TypeScript API using an OpenAPI 3.0 specification

After creating specifications for my REST API server using OpenAPI 3.0, I found myself wanting to generate an expressjs app quickly instead of manually writing repetitive code. However, the generated code from editor.swagger.io is in javascript, which does ...

Steps for running an Angular application in IntelliJ:1. Open IntelliJ IDEA

I'm currently navigating through IntelliJ to set up Angular support. https://www.jetbrains.com/help/idea/2017.1/using-angular.html#install_angular_cli After successfully creating the project, I am unsure of how to run it. My guess is that I need to ...

Setting a maximum limit for selections in MUI Autocomplete

Code updated to display the complete script logic. I want to restrict the number of selections based on a value retrieved from the database, but in this example, I have set it to 3 manually. The error message I'm encountering is "Cannot read properti ...

`Navigating seamlessly across multiple Angular applications`

Contemplating the use of Angular in a corporate setting, I am thinking ahead to having multiple applications. Does Angular support the use of multiple applications and sharing components? For instance, can I share a Navigation component? Update (2/1/19): ...

What is the best way to assign an index signature to a plain object?

Currently, I have this object: const events = { i: 'insert', u: 'update', d: 'delete' }; I am struggling to assign an index signature to the object. When I try the following: export interface EventsSignature { [key: ...

Display a browser alert in Angular 5 whenever a query parameter undergoes modification

In my web application, there is a Parent component called Item which has the route '/Item'. Within this Parent component, I have two children components: one is named Catalogue and the other is named AddSize. By default, when the page loads, th ...

"Angluar4 is throwing an error: it's unable to read the property 'iname' of

This is the code snippet from item.ts file:- export interface item{ $key?:string; available?:boolean; countable?:boolean; iname?:string; price?:string; desc?:string; image?:string; } The items component item.componenet.ts looks like this:- import { Com ...

Angular: monitoring changes in HTML content within a Component or Directive

I have a situation where I am retrieving HTML content from a REST endpoint using a directive and inserting it into a div element using [innerHTML]. Once this HTML content is rendered, I would like to manipulate it by calling a global function. My approach ...

Almost at the finish line with Angular version 14 and .NET Core 6 WebAPI setup on IIS!

Earlier someone pointed out that I had not added the hosting model, which I have now taken care of. When building the source code: Using Angular ng build , the output directory is set to /API (the dotnet core 6 project). This results in wwwroot being loc ...

A guide on incorporating dynamic formControlName functionality into AngularJs2

Currently, I am building forms using the form builder in AngularJS2. My goal is to incorporate the formControlName property/attribute into the form element as shown below: <input type="text" formControlName={{'client_name' + i}} placeholder=" ...

Is there a specific function that is triggered upon the successful completion of a subscription process?

I am facing an issue with the code below. The navigation is happening when a customer is created, instead of waiting for the address to be created successfully. Any assistance on this matter would be greatly appreciated. createCustomer(model: any) { ...

Unexpectedly, optimization causing issues on Angular site without explanation

Currently, I am utilizing Angular to construct a front-end website that searches for and showcases information obtained through API requests. Whenever I compile the project into a file bundle for static deployment using ng build, I notice that the resultin ...

Setting up Angular2 webpack to run behind a reverse proxy on a subpath

I am looking to configure angular2-webpack-starter behind an Apache reverse proxy with URLs starting with a fixed prefix like /angular2-webpack-starter/. I came across this setting: output: { publicPath:"angular2-webpack-starter", ... Is this the cor ...

What is the issue with assigning type {intrinsicattributes & true} or type {intrinsicattributes & false} in a React and TypeScript environment?

I am facing an issue with the following code snippet: function Parent() { const count1 = 2; const count2 = 4; const isCount = count1 < 0 || count2 < 0; //setting isCount here return show ? ( <Dialog> ...

Setting a variable based on the stage of its deployment in a DevOps environment: What you need to know

Is there a way I can easily update a variable in a React app based on the stage of an Azure DevOps release pipeline? For instance, if I have dev, QA, and production stages set up, and I want to change the client ID in the auth configuration for each envi ...

I encountered difficulties connecting mongoose to my local MongoDB server

Hello Everyone! Currently, I am in the process of linking my node.js project to mongodb. Initially, everything worked smoothly when I used mongodb atlas. However, when I attempted to connect it using mongodb compass, I faced some issues and nothing seemed ...

In what way can a piped operator in rxjs be influenced by the value returned by a subsequent operator?

When attempting to examine values between operators in an rxjs pipe, I decided to use tap to log them to the console. I added two taps, one before a map operator used for sorting an Array, and one after. Surprisingly, both taps logged the same sorted Arra ...

Issue: The canActivateChild method in the child guard is not functioning as

Following the Angular documentation, I attempted to implement a child guard in my code: @Injectable() export class AuthGuardService implements CanActivate, CanActivateChild { constructor(private authService: AuthentificationService, private router: Rou ...

Retrieve the dimensions of a child component when NgIf condition is met

I am facing a situation where I have a main component with a child component that is populated using NgFor. To control the visibility of the child, the parent sets a property called childIsVisible to false and binds it to the child using *ngIf="childIsVisi ...