如何在HTML中显示对象的变量名称?

时间:2019-06-26 18:45:14

标签: html

建立一个细节类以显示对象数据时,我似乎正在重复自己。是否可以使用* ngFor:对于rug对象的每个属性,显示该属性的名称,然后将其绑定到该对象的值?

//rug-detail.component.ts

   <div class="row">
        <div class="col-md-3">Name:</div>
        <div class="col-md-6">{{rug.name}}</div>
      </div>
      <div class="row">
        <div class="col-md-3">ID:</div>
        <div class="col-md-6">{{rug.id}}</div>
      </div>
      <div class="row">
        <div class="col-md-3">Availability:</div>
        <div class="col-md-6">{{rug.availability}}</div>
      </div>
      <div class="row">
        <div class="col-md-3">Price:</div>
        <div class="col-md-6">{{rug.price|currency:"USD":"symbol"}}</div>
//rug.ts

export interface Rug{
    name: string;
    id: number;
    availability: String;
    price: number;
}

对于Ruby,同样的问题:Accessing a variable's name from an object

1 个答案:

答案 0 :(得分:0)

提示:

rug = {
  name: "Name",
  id: 42,
  availability: "in stock",
  price: 123,
};

for (const key in rug) {
  console.log(`${key}: ${rug[key]}`)
}

// OR

for (const key of Object.keys(rug)) {
  console.log(`${key}: ${rug[key]}`)
}

两者之一必须在Angular的*ngFor

中可用