Home > Back-end >  How to use ngFor to access multiple object's value that is inside one big object in an HTML fil
How to use ngFor to access multiple object's value that is inside one big object in an HTML fil

Time:04-01

In angular , I am trying to use *ngFor in html file to access nested objects value . The object serverData I try to access is as followed.

{//whole object i try to loop through and access
  "0": {//inner , nested object that store the data I want to access 
    "District_en": "Sha Tin",
    "Name_en": "This will be the new name",
    "Address_en": "Kwei Tei Street, Fo Tan, Sha Tin",
    "Facilities_en": "2 barbecue pits",
  },
  "1": {
    "District_en": "Sha Tin",
    "Name_en": "Lok Shun Path Barbecue Area",
    "Address_en": "Lok Shun Path, Sha Tin",
    "Facilities_en": "6 barbecue pits",
  }
}

I am trying to print out each attributes specifically inside each "index" object.
With following code in html. Like loop through whole object and print out each property value.

 <tr *ngFor="let index of serverData |  keyvalue ">
     <td>{{index.value.District_en}}</td>
     <td>{{index.value.Name_en}}</td>
     <td>{{index.value.Address_en}}</td>
     <td>{{index.value.Facilities_en}}</td>
 </tr>

Yet error Object is of type 'unknown' comes up.
I was finding similar question, but most are about accessing multiple object.
My brain stop working when it turns into the situation of multiple object inside a single object ...
Thanks in advance.

CodePudding user response:

You can do like below.

app.component.ts

import { Component, OnInit } from '@angular/core';

interface ServerData {
  District_en: string;
  Name_en: string;
  Address_en: string;
  Facilities_en: string;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
  serverData: Record<string, ServerData>;

  ngOnInit() {
    this.serverData = {
      //whole object i try to loop through and access
      '0': {
        //inner , nested object that store the data I want to access
        District_en: 'Sha Tin',
        Name_en: 'This will be the new name',
        Address_en: 'Kwei Tei Street, Fo Tan, Sha Tin',
        Facilities_en: '2 barbecue pits',
      },
      '1': {
        District_en: 'Sha Tin',
        Name_en: 'Lok Shun Path Barbecue Area',
        Address_en: 'Lok Shun Path, Sha Tin',
        Facilities_en: '6 barbecue pits',
      },
    };
  }
}

app.component.html

<tr *ngFor="let index of serverData | keyvalue">
  <td>{{ index.value.District_en }}</td>
  <td>{{ index.value.Name_en }}</td>
  <td>{{ index.value.Address_en }}</td>
  <td>{{ index.value.Facilities_en }}</td>
</tr>

It is rendering properly on UI

Working Demo

Let me know if you have any doubt.

Note: Updated ts code

  • Related