如何使用 ngFor 访问 HTML 文件中一个大对象内的多个对象的值?

How to use ngFor to access multiple object's value that is inside one big object in an HTML file?

在 angular 中,我试图在 html 文件中使用 *ngFor 来访问嵌套对象值。我尝试访问的对象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",
  }
}

我正在尝试打印出每个“索引”对象中的每个属性。
在 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>

但出现错误 Object is of type 'unknown'
我发现了类似的问题,但大多数是关于访问多个对象。
变成一个物体里面有多个物体的情况,我的大脑就停止工作了...
提前致谢。

你可以像下面那样做。

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>

它在 UI

上正确呈现

Working Demo

如有任何疑问,请告诉我。

注意:更新了 ts 代码