简体   繁体   中英

how to access objects property name in angular template?

I want to bind a nested objects property name using angular interpolation

 <ng-container ngFor="let item of saleDetailsAggegater.productMap | keyvalue">
                            <tr *ngFor="let qtyMap of item.value | keyvalue">
                              <td>{{ item.key }}</td>
                              <td>{{qtyMap.value}}</td>
                              <td>{{Object.keys(qtyMap)[0]}}</td>
                            </tr>
                        </ng-container>

my saledetailsAggegater object is as follows

{"productMap":{"55478":{"priceQuantityMap":{"200.00":10}}},"taxMap":{},"paymentMap":{"1":970},"total":970}

but this line is not working as expected

<td>{{Object.keys(qtyMap)[0]}}</td>

how can i achieve this?

I don't think you can use native javascript functions in your template (angular won't parse them). You can however define the function on your component, and then use that in your template:

@Component({
  template: '<td>{{objectKeys(myObj)[0]}}</td>'
})
export class MyComponent {
  objectKeys = Object.keys;

  myObj = { displayThisKey: 'some-value' };
}

first you have a typo in your first ngFor , you forgot to put the * .
and you can achieve what you want by doing the following:

<ng-container *ngFor="let item of saleDetailsAggegater.productMap | keyvalue">
    <tr *ngFor="let qtyMap of item.value | keyvalue">
        <td>{{ item.key }}</td>
        <td>{{qtyMap.value | json}}</td>
        <td>{{qtyMap.key | json}}</td>
        <td>{{(qtyMap.value | keyvalue | json)}}</td>
    <td *ngFor="let qty of (qtyMap.value | keyvalue);">
      {{qty.key}}
    </td>
    </tr>
</ng-container>

I deleted {{Object.keys(qtyMap)[0]}} and added a json pipe just to make sure the object has the values you wanted. I also added multiple possibilities for you to choose from.
and here is a live demo: link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM