What is the best way to dynamically insert rows into an Angular material table using an array of rows?

Struggling to create a material table that features dynamic headers and rows populated by an array of strings. Unfortunately, I haven't been successful in displaying the rows within the table.

Check out the code here

<div *ngIf="customerResponse">
  <mat-table [dataSource]="customerResponse.customerDataRows">
    <ng-container *ngFor="let disCol of customerResponse.customerHeader; let colIndex = index"
      matColumnDef="{{ disCol }}">
      <th mat-header-cell *matHeaderCellDef>{{ disCol }}</th>
      <ng-container *ngFor="let disRow of customerResponse.customerDataRows;">
        <td mat-cell *matCellDef="">{{disRow}}</td>
      </ng-container>
    </ng-container>
    <mat-header-row *matHeaderRowDef="customerResponse.customerHeader; "></mat-header-row>
    <mat-row *matRowDef="let row; columns: customerResponse.customerHeader"></mat-row>
  </mat-table>
</div>

The headers are displaying correctly, sourced from the ts file, but I'm stuck on populating the rows data within the mat cell. Any assistance would be greatly appreciated!

Answer №1

I have adjusted the code slightly.

Within the Mat Cell Definition, I made changes to your code as follows:

<ng-container *ngFor="let disRow of customerResponse.customerDataRows;">
    <td mat-cell *matCellDef="">{{disRow}}</td>
</ng-container>

and updated it to:

<td mat-cell *matCellDef="let disRow">{{disRow[colIndex]}}</td>

The previous definition of *matCellDef was empty. By using colIndex as the key to access row data, we minimize errors in cases where a column from customerHeader is not part of the displayed columns and cells do not align correctly with the columns.

You can view the modified version of your stackblitz code here: https://stackblitz.com/edit/angular-ivy-2ngiqh?file=src/app/app.component.html

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

Mistakes following the modification of tsconfig.json and package.json

Recently, I delved into exploring the Ahead-of-time compilation cookbook for Angular and found it quite intriguing. However, it seems like the errors I am encountering are not directly related to my new venture. You can check out the cookbook here: https:/ ...

How can you utilize both defineProps with TypeScript and set default values in Vue 3 setup? (Typescript)

Is there a way to use TypeScript types and default values in the "defineProps" function? I'm having difficulty getting it to work. Code snippet: const props = defineProps<{ type?: string color?: 'color-primary' | 'color-danger&a ...

Using an asynchronous for loop to assign a background image to a div element

I am facing an issue with setting the background image of an observable array in my Ionic application. Here is the code snippet I am using: <ion-card *ngFor="let picture of pictures$ | async;" <div class="user-image" [ngStyle]="{'background- ...

Effective methods for transmitting reactive form control between child and parent components in Angular 2

I am working with a nested reactive form structure and I have the following setup: Parent HTML Code <form> <child-component></child-component> <button mat-raised-button color="primary">Save</button> </form> Child HT ...

Unlocking the capabilities of Chrome extensions using Angular 2 and TypeScript

Currently attempting to develop a chrome extension using angular2 and typescript, I have hit a roadblock in trying to access the chrome API (in this case, chrome.bookmarks). I have successfully gained access to the chrome object by following guidance from ...

You cannot assign type void to type any

I'm currently working on a component that involves some code: export class AddNewCardComponent { public concept = []; constructor( private _router: Router, private _empDiscService: empDiscService) { } ngOnIni ...

Deciding when to utilize an interface, when to avoid it, and when to opt for a constructor in Typescript for the creation of JavaScript arrays

Exploring the concept of JavaScript object arrays in TypeScript In my current project, I am retrieving a JSON array from an observable. It seems that I can define and initialize the array without necessarily specifying an interface or type. let cityList[ ...

It is not always a guarantee that all promises in typescript will be resolved completely

I have a requirement in my code to update the model data { "customerCode": "CUS15168", "customerName": "Adam Jenie", "customerType": "Cash", "printPackingSlip": "true", "contacts": [ { "firstName": "Hunt", "lastName": "Barlow", ...

The panning functionality on Android devices within the Firefox browser is currently experiencing issues with both panstart and pan

Currently, I am collaborating on an Angular7 project and utilizing hammerjs version 2.0.1. One of the tasks at hand is to allow panning functionality on a map for mobile devices. After testing on various android devices, I noticed that it performs well on ...

Creating an if statement based on the currently chosen option

My angular JS page includes a drop-down list: <div class="col-md-4 fieldMargin"> <div class="dropdownIcon"> <select name="actions" id="actions" ...

Why doesn't TypeScript automatically determine the prop type when Generics are used?

Below is the code snippet: interface MyInterface { a: { b: { c: "c"; }; }; } type ParentProps = keyof MyInterface type ChildProps<ParentProp extends ParentProps> = keyof MyInterface[ParentProp] type GrandChildType< ...

The onProgress event of THREE.JS Loader will only be triggered once the loading process has been successfully completed

Despite following numerous tutorials, I am struggling to receive regular updates on the loading progress when loading a model in order to create a loading icon. No matter what method I try, the onProgress function only triggers once, and that's after ...

Angular: Real-time monitoring of changes in the attribute value of a modal dialog and applying or removing a class to the element

I cannot seem to figure out a solution for the following issue: I have two sibling div elements. The second one contains a button that triggers a modal dialog with a dark overlay. However, in my case, the first div appears on top of the modal dialog due to ...

When a property is removed from a variable in an Angular Component, it can impact another variable

During the iteration of the results property, I am assigning its value to another property called moreResults. After this assignment, I proceed to remove array elements from the testDetails within the moreResults property. However, it seems that the remova ...

Customized interfaces utilizing generic components

Here is my simplified question. interface Identity{ name: string; } Next, we have a generic interface. interface State<T extends Identity>{ [T.name] : StateContainer<T> } Unfortunately, this approach fails and the following error is ...

Using properties to generate a header component in TypeScript

I am currently exploring TypeScript and incorporating it into a project for the first time. I'm encountering a challenge as I am not sure what to call this concept, making it difficult to search for solutions. If someone can provide me with the term, ...

Angular 4 HTTP Requests Failing to Retrieve JSON Data

I am currently working with the following method in my Typescript: allPowerPlants(onlyActive: boolean = false, page: number = 1): PowerPlant[] { const params: string = [ `onlyActive=${onlyActive}`, `page=${page}` ].join('&&apo ...

Filtering an array with radio buttons in Angular

I am working with a JSON list that contains various audio files categorized by genre, along with their corresponding URLs. export const musicList = [ { 'id': 0, 'catName': 'upload', 'audios': [ { ...

Implementing Limited Results in Redis FT.SEARCH with TypeScript

Snippet of code: client.ft.SEARCH('license-index-json',"@\\$\\" + ".reservedForApplicationName:GSTest",{ LIMIT: { from: 0, to: 1 } }) Error message: An error occurred when trying t ...

Obtaining the HTML element through ViewChild once the ngIf condition is met

I'm struggling with accessing my canvas element when its *ngIf condition is met. Let me provide some context to explain the issue. In my application, there's a canvas element (initially hidden) and a ViewChild element ref variable in my typescri ...