简体   繁体   English

如何访问 angular 模板中的对象属性名称?

[英]how to access objects property name in angular template?

I want to bind a nested objects property name using angular interpolation我想使用 angular 插值绑定嵌套对象属性名称

 <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我的saledetailsAggegater object如下

{"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).我认为您不能在模板中使用本机 javascript 函数(angular 不会解析它们)。 You can however define the function on your component, and then use that in your template:但是,您可以在组件上定义 function,然后在模板中使用它:

@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 * .首先,您的第一个ngFor中有错字,您忘记输入*
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.我删除了 {{Object.keys(qtyMap)[0]}} 并添加了 json pipe 只是为了确保 object 具有您想要的值。 I also added multiple possibilities for you to choose from.我还添加了多种可能性供您选择。
and here is a live demo: link这是一个现场演示: 链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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