0

I seem to be repeating myself when building a detail class to display object data. Is there a way to *ngFor: for each attribute of the rug object, display the attribute's name, and then bind it to the object's value?

//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;
}

The same question, for Ruby: Accessing a variable's name from an object

Jacob
  • 187
  • 1
  • 7

1 Answers1

0

A hint:

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]}`)
}

One of the two must be usable in Angular's *ngFor

Klímačka
  • 261
  • 1
  • 3
  • 16