Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NgFor with variable keys?

‘Headers’ (headers: any;) are keys extracted from’data.items[0]’ using ‘object.keys’.

How should i loop through ‘data.items’ objects. It doesn’t work if i try to loop though with *ngfor

this is the result i want.
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

But i am getting error when i use ‘item.header’,

Property ‘header’ does not exist on type ‘{ name: string; alias:
string[]; qty: number; price: number; total: number; }

if i try ‘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">  <---------- Problem 
            </td>
        </tr>
 </tbody>

>Solution :

You can create a type for the keys of an individual item and use that to index on an individual item:

type SaleTableHeader = "name" | "qty" | "alias" | "price" | "total";

// Component class
headers: SaleTableHeader[] = Object.keys(this.itemData.items[0]) as SaleTableHeader[];

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading