Can NgFor accept dynamic keys as variables?

'Keys' (keys: any;) represent the headers extracted from 'data.items[0]' using the 'object.keys' method.

How can I properly loop through the objects in 'data.items'? Using *ngFor does not seem to work as expected.

Here is the desired outcome: https://i.sstatic.net/aqtlc.png

However, I encounter an error when trying to access 'item.header',

The property 'header' does not exist on the type '{ name: string; alias: string[]; qty: number; price: number; total: number; }'

If I use 'item[header]'

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ name: string; alias: string[]; qty: number; price: number; total: number; }

CODE

Object

  private itemData: sale = {
    type: '',
    data: { date: ' ', InvoiceNo: ' ', tax: ' ' },
    total: { semitotal: 0, grandtotal: 0 },
    items: [
      { name: 'item 1', alias: ['01a'], qty: 0, price: 0, total: 0 },
      { name: 'item 2', alias: ['02a'], qty: 5, price: 250, total: 0 },
      { name: 'item 3', alias: ['03a'], qty: 6, price: 350, total: 0 },
      { name: 'item 4', alias: ['04a'], qty: 1, price: 150, total: 0 },
    ],
    params: {},
  };

Angular HTML Code

 <tbody>
        <tr *ngFor="let item of itemData.items" class="table-data" >
            <td *ngFor="let header of headers"> 
                <input type="text" [value]="item.header">  <---------- Issue
            </td>
        </tr>
 </tbody>

Answer №1

One approach is to define a specific type for the keys associated with an individual item, allowing you to easily index onto that item:

type ProductTableHeader = "name" | "quantity" | "description" | "price" | "total";

// Component logic
headers: ProductTableHeader[] = Object.keys(this.productData.items[0]) as ProductTableHeader[];

// Component Markup
<tbody>
  <tr *ngFor="let item of productData.items" class="table-row">
    <td *ngFor="let header of headers">
      <input type="text" [value]="item[header]" />
    </td>
  </tr>
</tbody>

Answer №2

One possible approach would be as follows:

HTML code snippet

<tbody>
    <table class="table">
    <th *ngFor="let header of itemData.items[0] | keyvalue" class="table-data"> 
        {{header.key}}
    </th>
    <tr *ngFor="let item of itemData.items" class="table-data" >
       <td *ngFor="let r of item | keyvalue">
        <input type="text" [value]="r.value">
       </td>
    </tr>
</table>
</tbody>

Desired Output:

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

Using a string array in a JSON model - a simple guide

Just starting out with Angular and having some difficulty integrating my JSON data effectively. Inside my service, I have temporary JSON data that is structured using a model to define the different types of information within it. My objective is to creat ...

Is it possible to utilize router-outlet within a component in a shared module?

My goal is to create a consistent user experience across all my feature modules by including a common sidebar in each of them. Currently, I am utilizing Bootstrap5 grids and a router-outlet within some grid elements to maintain a standardized look and feel ...

The system encountered an issue while trying to access the property 'play' of null

I'm attempting to create a customized audio player, but I've encountered an error: "cannot read property 'play' of null". After some research, I discovered that this could be due to the function being called before the ID exists. Howeve ...

EventListener cannot be removed

My TypeScript class is structured like this: class MyClass { let canvas: any; constructor(canvas: any) { this.canvas = canvas; this.canvas.requestPointerLock = this.canvas.requestPointerLock; document.exitPointerLock = ...

Creating dynamic Angular child routes with variable initial segment

Recently, I've been working on a new project to set up a blogging system. The next step in my plan is to focus on the admin section, specifically editing posts. My idea for organizing the routes is as follows: /blog - Home page /blog/:slug - Access ...

"Develop a unique Angular 12 custom pipe that retrieves data through a service and converts it into a string instead of

Hello Everyone, I've encountered a problem that I need help with. import { Pipe, PipeTransform } from '@angular/core'; import { PrintingTypesService } from 'src/app/settings/services/printing-types/printing-types.service'; import { ...

What could be the reason for receiving a TS message stating "Property 'value' may not exist on type 'boolean'. Did you intend to use 'valueOf'?" while updating state using RTK in React?

When attempting to create a slice using Redux Toolkit within the Visual Studio Code editor, I encounter a TypeScript warning that states "Property 'value' may not exist on type 'boolean'. Did you mean 'valueOf'?" This occurs w ...

Updating the FormArray index using Angular's `removeAt(i)` function does not reflect changes in the DOM

I initially suspected that there was an issue with my implementation, but it appears that the code I used to create a dynamic FormArray should be working, as indicated in this question I posted. However, when I integrate it into my project, the remove func ...

Is it possible to access 'import.meta' only within a module in an Angular micro front-end setup?

I have been incorporating mfe (module federation microfrontend) into my Angular project. However, I encountered an error in the console when trying to load the remoteEntry.js file: import.meta outside a module The version of Angular that I'm using is ...

Execute a function using a click event within a statement

Is it possible to trigger a function with parameters based on the result of a statement? For example, can we achieve something like this: (click)="datavalue.elementDataCollection.length > 1 ? AddNewDialog (datavalue,datavalue.COCLabel,mainindex,i) : r ...

Using brackets around or after an expression in Typescript

Exploring Typescript: Is there a distinction between the two square bracket notations? After running some tests, it appears they function equivalently. Any insights would be appreciated! interface test { a: string; b: string; } const x: test[] = [{a ...

Creating modern web applications using Angular and .Net Core with the power of Bootstrap 4

Has anyone experimented with developing an application using the following commands? dotnet new --install Microsoft.AspNetCore.SpaTemplates::* dotnet new angular You can find an example of this at this link. By default, the command creates an Angular + ...

To ensure optimal functionality, it is recommended to invoke the Angular Array Observable on two separate occasions

Just diving into Angular and encountering an issue with a button function that interacts with observables and array data. When I initially make a call, the array remains empty, but upon clicking the button again, it populates correctly. Perplexed by this b ...

Is there a way to refresh the current page in Ionic 3 when the browser is reloaded?

I have encountered a problem in my work with an Ionic 3 App. I am looking for a solution where the browser will refresh the current page instead of redirecting me to the home page. Is this achievable? I attempted to solve it using the following code: thi ...

Communication between parents and children is crucial for building strong relationships and providing validation

This question may have been asked in a complex manner before, but I will simplify it here. In my main component, I have a form tag and Submit Button. Within this component, there is a child component that contains an input field with a required attribute, ...

What are some techniques for creating an HTML element that remains fixed on the page after scrolling past a certain height, even though it is originally part of

I am trying to achieve a specific effect with a <section></section> element on my web page. Once the user scrolls past the section, I want it to remain fixed at the top of the screen even as they continue scrolling downwards. This is in an Ang ...

What is the best way to attach a function as an Angular filter predicate?

Struggling with the binding of a function to 'this' in my typescript and angular project. It's important to note that the controller and $scope are distinct entities in this scenario. Tried using angular.bind(this, this.filterViewedStagingI ...

Ways to enhance a component by incorporating default properties in React/TypeScript

I am looking to enhance a React/TS component (specifically the @mui/x-data-grid DataGrid) by populating the classes prop with my own application classes. Initially, I thought about creating a new component called CustomDataGrid like this: import React fro ...

Upon initial page load, the distinctUntilChanged() function will not be triggered

Upon loading a page, I initiate the following method and utilize the returned list in a dropdown menu. The tap and switchMap functions are run as expected, however, the distinctUntilChanged function does not execute upon page load. Once the page is loade ...

Two-way data binding between TypeScript and HTML FormGroups

Attempting to create my first Reactive form in Angular Here is the code : import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl } from "@angular/forms"; @Component({ selector: 'app-username-password ...