What is the best way to display every single column from the datasource in an Angular material table?

Currently, I am attempting to create an Angular material mat-table using the resources provided in the official documentation found at this link.

The table I am working on consists of approximately 10 columns. Is there a way to dynamically display all the columns available in the data source without manually specifying ten separate attributes in the HTML code?

Answer №1

To display columns and headings using *ngFor, you can use the Angular *ngFor directive; for the actual values, write the corresponding code in the TS file.

Here is the relevant HTML code snippet:

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

    <ng-container *ngFor='let disCol of displayedColumns; let i = index'>
        <ng-container matColumnDef="{{disCol}}">
            <th mat-header-cell *matHeaderCellDef> {{disCol}} </th>
            <td mat-cell *matCellDef="let element"> {{returnVal(element, disCol)}} </td>
        </ng-container>
    </ng-container>

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

And here is the relevant TS code snippet:

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

export interface PeriodicElement {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [
  // Data objects
];

@Component({
  selector: 'table-basic-example',
  styleUrls: ['table-basic-example.css'],
  templateUrl: 'table-basic-example.html',
})
export class TableBasicExample {
  displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
  dataSource = ELEMENT_DATA;

// Function to return values based on column type
    returnVal(element, dispCol){
      switch(dispCol){
        case 'position': return element.position;
        case 'name': return element.name;
        case 'weight': return element.weight;
        case 'symbol': return element.symbol;
      }
    }
}

You can see a complete working example on 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

Guidelines for incorporating Dropdown menus in a Multi-level Carousel themed SideNav using Angular 5 Material

https://i.sstatic.net/cbmuA.gif Hey there, World! I've been working on a sidenav with tabs that has the perfect transition effect I was looking for. Now, I want to add functionality so that when users click on "Option 1, Option 2 or Option 3", the tab ...

Navigating IntelliSense Overload Signatures in VSCode

Searching for a solution in VSCode to navigate through multiple overload signatures in TypeScript and JavaScript? Occasionally, when using IntelliSense, a tooltip appears with hints like (+1 overload) while typing "someObj.someMethod(", displaying the fir ...

ERROR: PipeError - Conversion of "Invalid Date" to a date is not possible for the DatePipe

While attempting to format a date with time, I ran into an error. The way I am sending the request is as follows: created = this.datePipe.transform(dateCreated, 'yyyy-MM-ddTHH:mm'); I require the time in order to consume a service that necessi ...

Using Typescript to declare types for an object that is capable of generating an outcome

If I have an object structured like this let obj = { property1:()=>{ return Date()} // for example, it doesn't have to be a date property2:()=>{ return 1} } Now, I want to convert this to the following type structure { property1: ...

`Square payment integration using the mean stack technology stack`

Seeking advice on how to integrate Square payment form with angular and node. The form functions properly, but upon hitting send, it fails to post to /process-payment. As a newcomer to the MEAN stack, I am unsure where to start regarding using angular and ...

Sending an image in the body of an HTTP request using Angular 7

I'm currently in the process of developing an Angular application that captures an image from a webcam every second and sends it to a REST API endpoint for analysis. To achieve this, I have implemented an interval observable that captures video from t ...

What is causing the ngModelChange event to be triggered every time the input box gains or loses focus?

example.html <input #gb type="text" pInputText class="ui-widget ui-text" [(ngModel)] ="filterText" (ngModelChange)="filterText = $event; clearFilter(filterText)"/> script.js clearFilter(value) { alert(value);// the value is curr ...

Modify the icon for the angular material datePicker

I was pondering the possibility of changing the icon displayed when using the datePicker feature in Angular Material. Here is the code snippet provided in the Angular Material documentation. <md-input-container> <input mdInput [mdDatepicker]=" ...

Does anyone have experience using the useRef hook in React?

Can someone help me with this recurring issue: "Property 'value' does not exist on type 'never'" interface InputProps { name: string; icon?: ReactElement; placeholder?: string; } const Input = ({ name, icon: Icon, ...rest }: Inpu ...

Angular user profile update button not functioning as expected

We are currently implementing Angular alongside Node.js Express. Our issue arises when attempting to update user details from the settings page, as clicking the update button triggers the following error: Failed to load resource: net::ERR_CONNECTION_RESET ...

What is the best way to create a TypeScript type for React props that only allows prop B to be used if prop A is included in the component?

My component Text has 2 props: isHideable: boolean and hidden: boolean. How can I only allow Hidden as a prop when isHideable is set to true? Currently, both isHideable and hidden are being accepted which is not the desired behavior: type Props = { chi ...

Accessing Parent Component's Route Parameters in Child Component in Angular 5

Here we have the add-new-folder.component, which functions as a child component of the folder.component. When routing to the add-new-folder.component from the parent folder.component, I need to access the userid parameter of the parent component in its chi ...

Utilizing a TypeScript function to trigger an action from within a Chart.js option callback

Currently, I am utilizing a wrapper for Chart.js that enables an animation callback to signify when the chart has finished drawing. The chart options in my code are set up like this: public chartOptions: any = { animation: { duration: 2000, ...

Waiting for Subscribe in other method in Angular RxJS

@Component({ selector: 'note-consultant', template: '<div> <div>{{patientInformation}}</div> <textarea #textElemRef></textarea> <button (click)="onSave()">Done</button> </div&g ...

Data retrieved from API not displaying in Angular Material table

I've hit a roadblock trying to understand why my mat-table isn't displaying the data for me. I'm working with Angular 15 and using Angular Material 15. Below is my HTML component code: <mat-divider></mat-divider> <table mat-t ...

The most suitable TypeScript type for a screen being utilized again in react-navigation v5

When it comes to typing screens under react-navigation v5, I usually follow a simple pattern: // Params definition type RouteParamsList = { Screen1: { paramA: number } Screen2: undefined } // Screen1 type Props = StackScreenProps<R ...

Could you confirm if my understanding is correct, that running ng update --all will only display the available upgrade options

After running the command ng update A list of items is displayed, including @angular/cdk 6.4.7 > 8.2.0 ng update @angular/cdk ... ... There may be more packages that are outdated. You can also try running ng update --all to update all at once. ...

Using ngrx store select subscribe exclusively for designated actions

Is it possible to filter a store.select subscription by actions, similar to how we do with Effects? Here is an example of the code in question: this.store .select(mySelector) .subscribe(obj => { //FILTER SUBSCRIPTION BY ACTION this.object = ob ...

"Having trouble subscribing? The first attempt doesn't seem to be working

I'm currently working on some TypeScript code that searches for the nearest point around a user in need of car assistance by checking a database. Once the nearest point is identified, the code retrieves the phone number associated with it and initiate ...

Tips for preloading icon font in Angular server-side rendering (SSR)

Is it possible to preload icons and fonts before the HTML content is rendered? I have been using a preload strategy to try and achieve this. index.html <!doctype html> <html lang="en"> <head> <meta charset="utf-8&quo ...