Tweaking the column name and data values within a mat table

Exploring Angular and currently using Angular CLI version 8.1.0.

I have two APIs, as shown below:

For bank details:

 [
        {
            "strAccountHolderName": "Sarika Gurav",
            "strAccountNumber": "21563245632114531",
            "bankName": "IFSC",
            "ifsc": "IFSC00014",
            "branch": "Tardeo"
        }
    ]

For KYC details

[
    {
        "strCompanyRegNumber": "123456",
        "strGSTNumber": "11242",
        "strAadharNumber": "3412345667",
        "createdOn": "2020-02-01 09:29:19.723600"
    }
]

I have a material table on the first page displaying a list of requests for bank and KYC. When selecting a "bank" row, I want to display the aforementioned information on the next page. While I am able to render the API data on the HTML Page, my goal is to present it in the material table.

In addition, I aim to dynamically change the column names according to the request type.

For bank requests, I intend to display the following information:

Account Holder Name: Sarika Gurav
Account Number: 21563245632114531
Bank Name: IFSC

And for KYC requests:

Company Registration Number: 123456
GST Number: 11242
Aadhar Number: 3412345667

approval.component.html

<h5>Additional Details</h5>
    <table mat-table [dataSource]="additionalDetailsDataSource" class="mat-elevation-z1">
        <ng-container matColumnDef="item">
        <td mat-cell *matCellDef="let services" class="item-name"> {{services.item}} </td>
        </ng-container>

        <ng-container matColumnDef="value">
        <td mat-cell *matCellDef="let services"> {{services.value}} </td>
        </ng-container>

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

approval.component.ts

this.apiService.getVendorById(col,id,rid)
      .subscribe(data=>{
        this.result = data[0]; 
      });

The API results are stored in the "result" variable.

To display them on the HTML page, I use: {{result?.strAccountHolderName}}

If there's a way to dynamically modify the column names on the material table, any insights are appreciated!

Answer №1

To begin, start by modifying your HTML file:

<table mat-table [dataSource]="dataSource" class="mat-elevation-z1">
        <ng-container matColumnDef="key">
        <td mat-cell *matCellDef="let element" class="item-name"> {{element.key}} </td>
        </ng-container>

        <ng-container matColumnDef="value">
        <td mat-cell *matCellDef="let element"> {{element.value}} </td>
        </ng-container>

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

Now, in your TypeScript file:

 interface Data {
      key: string;
      value: string;
    }
dataSource: Data[] = [];
  displayedColumns: string[] = ['key', 'value'];

 this.apiService.getVendorById(col,id,rid)
      .subscribe(data=>{
      this.result = data[0];

      const newdata: Data[] = [];
      for (const prop in this.result) {
      newdata.push({
      key: [prop],
      value: this.result[prop],
      })
      }     
      this.dataSource = newdata;


});

Answer №2

If you need to show a column name in your table:

    <table mat-table [dataSource]="additionalDetailsDataSource" class="mat-elevation-z1">
        <ng-container matColumnDef="item">
            <th mat-header-cell *matHeaderCellDef>
              ADD YOUR COLUMN HEADER NAME HERE
            </th>
            <td mat-cell *matCellDef="let services" class="item-name"> {{services.item}} </td>
        </ng-container>
...
        <tr mat-row *matRowDef="let row; columns: additionalDetailsDisplayedColumns;"></tr>
    </table>

I am unsure of what you are looking for next. Perhaps you are interested in an Expandable row? https://i.sstatic.net/2eHzX.png

Take a look at https://material.angular.io/components/table/examples and the "Expandable row" section for guidance on implementation.

Answer №3

Perhaps I didn't fully grasp the question, but if you simply need to modify the column name, you can achieve this by incorporating a mat-header:

<h5>Additional Information</h5>
<table mat-table [dataSource]="additionalDetailsDataSource" class="mat-elevation-z1">
    <ng-container matColumnDef="item">
    <th mat-header-cell *matHeaderCellDef>{{ services.header }}</th>
    <td mat-cell *matCellDef="let services" class="item-name"> {{services.item}} </td>
    </ng-container>

    <ng-container matColumnDef="value">
    <td mat-cell *matCellDef="let services"> {{services.value}} </td>
    </ng-container>

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

If you wish to dynamically change the table columns, it's a bit more complex. As far as my knowledge goes, there are two approaches:

  1. You can predefine all possible columns in both the .html and .ts files, then adjust which columns are visible by manipulating "additionalDetailsDisplayedColumns" in your typescript file
  2. If you're unsure of all potential columns or it's not practical to build them beforehand, you can recreate the table based on user input. In this scenario, utilizing @Input to pass the columns is useful. With @Input, you can update not only column names but also any content, triggering a table rebuild with each change.

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

Establish a connection between a variable and the selected value of Mat-select using a form

Within my TypeScript code, there exists a variable named type whose value is provided by its parent component. This type value is essentially a string that has the possibility of being empty upon being received from the parent component. Additionally, in t ...

Rendering a Nativescript component once the page has been fully loaded

I'm currently working on integrating the WikitudeArchitectView into my TypeScript code. I've successfully registered the element in the main.ts TypeScript file: var architectView = require("nativescript-wikitudearchitectview"); registerElement ...

Ways to access a nested route in Angular 4

My routing configuration is set up as depicted below: export const Approute: Routes = [ { path: '', component: DashboardComponent }, { path: 'add-course', component: AddCourseComponent }, { path: 'bui ...

Establish a global variable within a TypeScript file

I am currently facing an issue where I need to add an event to the browser inside the CheckSocialMedia function. However, it keeps saying that it could not find the name. So, my question is how do I make the 'browser' variable global in the .ts ...

Is there any distinction between using glob wildcards in the tsconfig.json file when specifying "include" as "src" versus "include" as "src/**/*"?

Is there a distinction between these two entries in the tsconfig.json file? "include": ["src"] "include": ["src/**/*"] Most examples I've come across use the second version, but upon reviewing my repository, ...

One if statement encompassing two conditions

Is there a way to combine two conditions in a single if statement in Angular 9+? I am looking for a solution where both conditions need to be met for my HTML element. Currently, I have attempted this: <div *ngIf="(params.folder!= 'folder1&ap ...

Troubleshooting: Unable to Open Page with Google Material Button in Angular 5

Currently, I'm facing an issue with a button that is not opening to a new site despite following what seems like simple steps. <button mat-raised-button href="https://www.google.com/" color="primary">Connect with Stripe</button> I even a ...

Using TypeScript with Angular: encountering a ReferenceError stating that the System object is not defined in the System

I attempted to follow a tutorial to set up Angular 2 with TypeScript from the following link: https://angular.io/guide/quickstart However, I encountered the following error: ReferenceError: System is not defined System.config I am uncertain why this e ...

Is it possible to include if else logic code within a catch statement?

There's a nagging feeling within me that having logic code within a catch statement is not the right approach. For example, my catch block currently looks like this: try{ // do some stuff that throws some unexpected errors } ...

Combining attributes of objects in an array

Is the title accurate for my task? I have an array structured like this: { "someValue": 1, "moreValue": 1, "parentArray": [ { "id": "2222", "array": [ { "type": "test", "id": "ID-100" }, { ...

What is the best method for building and deploying an Angular-CLI 4 project across multiple environments?

We are in the process of deploying Angular to an Amazon S3 static website. Currently, we are creating separate builds for each environment (development and production). Is there a way to build once and deploy to all environments effortlessly? Thank you in ...

Exploring methods to retrieve the status attribute of an Angular httpClient response

Here is the code snippet that I am working with: this.http.post(url, payload) .subscribe( (req:any)=>{ if(req.status != 200){ console.log('non 200 status'); The this.http in my code refers to a service tha ...

Issue with rendering of material icon

I'm having trouble properly rendering a material icon in my project. I've installed it correctly, but it's not showing up in the browser. Here are the steps I followed: npm install material-design-icons In my .angular-cli.json file, I mad ...

Guide to swapping out embedded objects within a TypeScript data structure

I am in need of modifying a TypeScript object by conducting a key search. It is important to note that the key may be repeated within the object, so I must ensure it belongs to the correct branch before making modifications to the corresponding object. To ...

Is Cognito redirect causing issues with Angular router responsiveness?

When employing social login via AWS Cognito, Cognito sends a redirect to the browser directing it to the signin redirect URL after signing in. In this case, the specified URL is http://localhost:4200/home/. Upon receiving this redirect, the application in ...

Stop the reactive form from automatically submitting and instead manually send a POST request to the server

I'm facing a small issue with my form submission. When I try to submit an empty form, it sends a post request to my server, and I'm unsure how to prevent that from happening. Below is my form structure: <form class="form-horizontal" [ ...

data not corresponding to interface

I am encountering an issue that says Type '({ name: string; href: string; icon: IconDefinition; } | { name: string; href: string; icon: IconDefinition; childs: { name: string; href: string; icon: IconDefinition; }[]; })[]' is missing the followin ...

Tips for extracting a particular subset from an array containing JSON objects using Angular

Hey there, I have a collection of JSON objects and I've been able to showcase them one by one using Angular (in this case, I'm building a blog). The JSON objects are retrieved through an HTTP GET request. On my landing page, I display the blog ...

What is the best practice for inserting typescript definitions and writing them when the object already has a pre-existing definition?

Apologies for this question, as I am struggling to find the necessary information due to my limited understanding of Typescript. I have integrated a jquery plugin called typeahead and added a global variable named bound on the window object for communicati ...

I encountered a problem where the error "Type '(err: Error) => void' does not possess any properties similar to type 'QueryOptions'" appeared, and I am unsure of the underlying cause

Check out my route for removing a user: https://i.stack.imgur.com/fevKI.png I've set up a route called "/deleteuser" that uses the POST method. It validates the request body for an id and then proceeds to delete the user with that ID from the databas ...