Is there a method to add columns to an Angular material table dynamically?

I'm encountering an issue with creating dynamic tables using Angular Material tables. Since the table is reliant on an interface, I have a set number of columns. What I'm aiming for is to generate a table dynamically based on the server's response. Is there a method to create the interface dynamically or something similar? The reason behind this query is that the application might have varying numbers of columns - sometimes 2, other times 3, depending on the array size. My current interface structure appears as follows:

export interface Data {
    file: any,
    typea: any,
    typeb: any
}

Based on this interface, I have 3 columns defined. While there are at least 3 columns present, more may be required depending on incoming data. Unfortunately, I haven't been able to achieve this yet. Any assistance in this matter would be greatly valued.

Answer №1

If you want to easily manage multiple columns in a table, one approach is to store all possible columns in an array called definedColumns. You can then loop through this array to define the headers and cells for each column.

To control which columns are displayed based on certain conditions, create another array named columnsToDisplay containing the names of the columns you wish to show. By adding or removing column IDs from this array, you can dynamically update the table to display the desired columns.

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

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

You can see a working example of this concept on the Angular Material website under "Table dynamically changing the columns displayed" in the examples section here - https://material.angular.io/components/table/examples


If you need more advanced features, like using TemplateRefs for cell and header definitions, consider exploring Angular Material's CDK functionalities.

For dynamically adding and removing columns from a table using Angular CDK API, you can assign #table to your mat-table element and access it in your component as a @ViewChild. Then, you can utilize this.table.addColumnDef to add new columns as needed. Check out https://material.angular.io/cdk/table/api#CdkColumnDef for more information.

Answer №2

While I'm not completely sold on angular-material tables, they do offer the functionality to generate dynamic properties for your Data object following a server request.

The code snippet provided is in JavaScript and can easily be ported over to TypeScript, where the promise represents an HTTP call.

var obj = { };
var promise = new Promise(resolve => resolve(['one', 'two', 'three']));

promise.then(data => {
  for (let column of data){
    obj[column] = 'data -> ' + column;
  }
  
  console.log(obj);
});

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

Angular: Modules that are lazily loaded are only loaded into memory and executed, but

I am facing an issue with lazy loading in my Angular application. I have an AppModule that lazily loads MainModule, which in turn lazy loads HomeModule. The problem is that while MainModule loads fine, HomeModule gets loaded but is not rendered inside the ...

Tips on how to navigate to a specific section within a div using an angular page component

Is there a way to automatically redirect to a specific section within a div on an Angular page after saving? For example, after performing a save action, I want to be able to navigate directly to a particular div within the page using something like this ...

POST requests in Angular Universal are making use of the IP address assigned to my server

My Angular Universal application (version 5.2.11) is currently hosted on Heroku, running on a Node server using express. I have implemented rate-limiters in all my POST routes to restrict requests by IP address, checking the request's IP through req.h ...

Mocking store.dispatch in Jest with TypeScript did not result in any function calls being made

Testing Troubles I'm a beginner in the world of testing and I'm facing some challenges. Despite going through all the documentation on jest, I couldn't find information specific to TypeScript cases. Currently, I'm on a quest to figure ...

Removing curly braces and double quotes from an array object can be achieved by iterating through each element

Within this particular project, I have utilized Angular 8 and TypeScript. In the implementation, there exists an array that showcases emails either through user input or via CSV upload. Once the user inputs several emails, a button is available to send in ...

Guide to creating varying component sizes using ReactJS and Styled Components

Is it possible to add variation to my button based on the prop 'size' being set to either 'small' or 'medium'? interface Props { size?: 'medium' | 'small'; } How can I adjust the size of the component us ...

An asynchronous function operates incessantly

I have implemented the following code in React using hooks to fetch data from two different sources. const [ permissionTree, setPermissionTree ] = useState([]); const [ availablePermissionsInRole, setAvailablePermissionsInRole ] = useState<Permission[] ...

Is Axios the sole option for API calls when utilizing Next.js with SSG and SSR?

Can someone clarify the best practice for data fetching in Next.js? Should we avoid using axios or other methods in our functional components, and instead rely on SSG/SSR functions? I'm new to Next.js and seeking guidance. ...

Using Angular 5+ to fetch information from an ASP.NET Core Web API

Having trouble retrieving data from an ASP.NET Core 2.0 Web API with Angular 5+. The steps taken so far are as follows: An ASP.NET Core 2.0 Web API was created and deployed on a server. Data can be successfully retrieved using Postman or Swagger. Using ...

Challenges in handling asynchronous data within static JSON objects in Angular2

I have a service set up with some static objects that are being utilized in my UI. fetchRulesVariables() fetchRuleVariables() { let variables = [ { name: 'Credit Funding Type', id: 1, multiple: ...

What steps can be taken to ensure a successful request to a Node.js server when previewing an Angular app on a separate device within the same network?

My desktop computer hosts the Angular front-end on port 4200 and the Express.js back-end on port 4000. When I try to access the Angular app from my mobile Android phone using 192.168.1.X:4200, the app loads but doesn't display any data from the Expres ...

Attempting to publish and install a unique angular2 component using NPM and Angular-CLI results in successful compilation only on the initial try

I am facing a peculiar and frustrating issue. The problem revolves around an Ng2 component I have developed called via-date-picker. My goal is to publish it on NPM so that it can be easily utilized in other projects. To achieve this, I converted it into a ...

Launching React Native in Visual Studio Code: launchReactNative.js

Struggling to get visual studio code to create the launchReactNative.js file in the ./vscode directory. I've been attempting to configure a react-native project with typescript on visual studio code to debug typescript files, but all my efforts have ...

Using Typescript to extract/calculate types with limitations without the need to explicitly extend or broaden them

I have a function called build that constructs a User object using the provided parameters. I want to define the function in such a way that it recognizes which parameters are being passed and incorporates them into the return value. Initially, I thought ...

Creating a variable as a list of string arrays in TypeScript

Currently working with Angular 2.0, I am trying to declare a variable in a Typescript file that is a list of string arrays. I attempted using yAxis_val: list, but it is not functioning correctly. If anyone knows the proper way to achieve this, please prov ...

Arranging an array in Angular 7 with various states and numbers

Looking to tackle this array sorting issue in Angular 7, the data is fetched from the API: "Products": [ { "ProductCode": "MC30180", "Description": "Description_1", "NationalCode": "N.C. 0965", "Pend ...

How can I specify a "router" member variable in Angular?

In Angular 9, I am working on a parent component where I need to pass a function to a child component. Specifically, I want to pass the "onNavigate" function to the child component... import { Router, ActivatedRoute } from '@angular/router'; ... ...

What is the best way to retrieve the current value of an *ngFor loop upon button click?

I have been attempting to retrieve the data.login value of the data item that the user has clicked on the avatar image. Despite my efforts, I have not been able to successfully achieve this through various methods found online. How can I access the current ...

Learning how to use arrow functions with the `subscribe` function in

Can someone help clarify the use of arrow functions in TypeScript with an example from Angular 2's Observable subscribe method? Here's my question: I have code that is functional: this.readdataservice.getPost().subscribe( posts =&g ...

Is it feasible to pre-render an Angular2 view invisibly when hovering?

Can a view be preloaded and prerendered invisibly upon hover? I have an application that displays a list of items. Each item is its own component, and when you click on any of these items, it is replaced by a detailed view (another component) of the same ...