What's the best way to insert values into data binding within a Typescript/ Angular mat Table?

Objective: Create a dynamic table using JSON data

 <mat-table class="mat-elevation-z8" *ngIf="carrierRates" [dataSource]="carrierRates">
        <ng-container *ngFor="let columnName of columnsList" matColumnDef="{{columnName}}">
            <mat-header-cell *matHeaderCellDef>{{columnName}}</mat-header-cell>
            <mat-cell *matCellDef="let itemRate">
                {{itemRate.$columnName}}
            </mat-cell>
            <mat-footer-cell *matFooterCellDef></mat-footer-cell>
        </ng-container>
<mat-header-row *matHeaderRowDef="columnsList;"></mat-header-row>
        <mat-row *matRowDef="let row; columns: columnsList;"></mat-row>
        <mat-footer-row *matFooterRowDef="columnsList"></mat-footer-row>

    </mat-table>

Inquiry 1: How can I iterate through the column list and data source in separate loops?

Inquiry 2: What is the correct method to pass the value of columnName in this line {{itemRate.$columnName}}

Note: columnName represents the keys in the JSON object

{"planId":"abcd",
"rateAreaId":"lmpo",
"singleMonthly":0,
"twoPeopleMonthly":0,
"familyMonthly":0}

Answer №1

  1. Instead of using 2 nested loops, you can streamline your code by defining templates for columns and rows separately.

Define each column with a unique name and specify the header content along with the data it should display for each row. For example, create a column named planId to show the Plan ID:

<ng-container matColumnDef="planId">
  <th mat-header-cell *matHeaderCellDef> Plan ID</th>
  <td mat-cell *matCellDef="let itemRate"& gt; {{itemRate.planId}} </td>
</ng-container>

Continue this process for other columns as well.

  1. The column names you'll be working with are planId, rateAreaId, singleMonthly, twoPeopleMonthly, familyMonthly. Create a variable columnList in your component file containing these column names:

columnList = [planId, rateAreaId, singleMonthly, twoPeopleMonthly, familyMonthly];

Add mat-header-row and mat-row within your mat-table component, and pass columnList as inputs:

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

Note: You can rearrange and customize the displayed columns dynamically by altering the order or selection of columns in your columnList.

This flexibility allows you to easily manage the layout of your table based on changing requirements.

I've summarized some key points from the extensive Angular Material Table documentation ;)

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

Eslint highlighting the initial function declaration within a Vue script

I'm currently creating a Vue file using a Typescript script, and encountering an unusual Eslint "error." The issue arises on line 15 with this specific complaint: Parsing error: Unexpected token, expected "," Interestingly, this error only occurs wi ...

Creating IPv6 Mask from IPv6 Prefix Using Javascript: A Step-by-Step Guide

Write a JavaScript/TypeScript function that can convert IPv6 prefixes (ranging from 0 to 128) into the corresponding mask format (using the ffff:ffff style). Here are some examples: 33 => 'ffff:ffff:8000:0000:0000:0000:0000:0000' 128 => ...

Angular - Facing issues with CORS for every request made

Currently, I am developing an angular 12 application for my university with a java back-end. While testing Angular's http client, I encountered an issue where CORS is blocking my requests. const API_URL = 'http://localhost:9080' @Injectable ...

Performing a HTTP GET request in Angular 2 with custom headers

I recently came across some posts discussing how to set headers in a GET request. The code snippet below demonstrates one way to do this: let headers = new Headers({ 'Accept': 'application/json' }); headers.append('Authorization&a ...

There is an issue with the Next.js middleware: [Error: The edge runtime is not compatible with the Node.js 'crypto' module]

Struggling with a problem in next.js and typescript for the past 4 days. If anyone can provide some insight or help with a solution, it would be greatly appreciated. Thank you! -- This is my middleware.ts import jwt from "jsonwebtoken"; import { ...

Ways to cite a vendor in static class functions?

Is there a method to access a service provided at bootstrap within static class methods? I don't have any code to share right now, but I've been experimenting with the standard syntax using Injector (you can find more information here). Whenever ...

Obtaining child component references in Angular using @ViewChildren

Currently, I am generating several ModuleItemComponents by utilizing the following Angular syntax: <div #moduleItems *ngFor="let module of seriesItem.modules; let i = index"> <app-module-item [videoModule]="module" >< ...

Leverage the TypeScript Compiler API to verify whether an interface property signature permits the value of undefined (for example, prop1?:

Currently, I am utilizing the TypeScript Compiler API to extract Interface information in order to generate database tables. The process is functioning effectively, however, I am seeking a method to determine if certain fields are nullable, or as it is phr ...

CoursesComponent does not contain a Directive annotation

I have been following a tutorial online at this link: https://www.youtube.com/watch?v=_-CD_5YhJTA Unfortunately, I keep encountering the following error message: EXCEPTION: No Directive annotation found on CoursesComponent Here is an excerpt from my a ...

Incorporating a TypeScript module into a JavaScript module within a React application

I'm encountering an issue with my React app that was created using create-react-app. I recently added a Typescript module to the project, which is necessary for functionality reasons. Although it will remain in Typescript, I made sure to install all t ...

What is the best way to define a signal within a class interface in Angular 17?

I’m working on setting up signals for my properties in class, which has been going smoothly so far. public varName = signal(''); However, I would also like to utilize the related interface. Unfortunately, I have not come across any documentati ...

What causes TypeScript to interpret an API call as a module and impact CSS? Encountering a Next.js compilation error

My website development process hit a roadblock when I tried integrating Material Tailwind into my project alongside Next.js, Typescript, and Tailwind CSS. The compilation error that popped up seemed unrelated to the changes, leaving me baffled as to what c ...

Activate combineLatest from a different component

I am working with component A and B. Within component A's ngOnInit, I am using combineLatest to load the initial data. this.filteredProduct$ = combineLatest([ this.productDataList$, this.productFilterApplied$, this.collectionFilterApplied$, th ...

How can I define the type of a constructor that requires a parameter in TypeScript?

Having identified the issue, let's focus on a minimal example: // interfaces: interface ClassParameter{ x:number } interface ClassParameterNeeder{ y:number } type ClassParameterConstructor = new () => Cla ...

Angular: Updating image tag to display asynchronous data

Utilizing Angular to retrieve user profile pictures from the backend, specifically Node.js/Express, has been mostly successful. However, there is one issue that I have encountered. The HTML displaying the profile picture does not re-render when the user up ...

Creating a TypeScript type that extracts specific properties from another type by utilizing an array of keys

In my TypeScript journey, I am working on crafting a type that can transform a tuple of keys from a given type into a new type with only those specific properties. After playing around with the code snippet below, this is what I've come up with: type ...

Yes, it's not able to retrieve the value from headlessui combobox

I have encountered an issue while using the Headlessui combobox component in conjunction with Yup. Despite successfully storing the selected value in the selectedMemory state variable, Yup consistently generates a required error message. I seem to be overl ...

Exploring ways to display all filtered chips in Angular

As a new developer working on an existing codebase, my current task involves displaying all the chips inside a card when a specific chip is selected from the Chip List. However, I'm struggling to modify the code to achieve this functionality. Any help ...

Having trouble deleting a component from an array in React?

I am facing an issue with my array and component functions. Each component has a handleRemove function that is supposed to remove the selected component from the array. However, the function is not working as expected. Instead of deleting just the selected ...

Choose between creating an observable pipe within a function or storing it in a variable

Currently, I have a functional code snippet that leverages the Angular service to create an Observable pipeline. This pipeline utilizes operators like mergeMap, filter, map, and shareReplay(1) to manage user authentication and fetch the onboarding status f ...