首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用ngFor访问一个文件中一个大对象内的多个对象的值?

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

Stack Overflow用户
提问于 2022-03-31 07:04:32
回答 1查看 135关注 0票数 0

在角度上,我试图在html文件中使用*ngFor来访问嵌套的对象值。我试图访问的对象serverData如下所示。

代码语言:javascript
复制
{//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中使用下面的代码。循环遍历整个对象并打印出每个属性值。

代码语言:javascript
复制
 <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'出现了。

我发现了类似的问题,但大多数都是关于访问多个对象的。

当它变成一个物体内的多个物体时,我的大脑就停止工作.

提前谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-31 07:10:19

你可以像下面这样做。

app.component.ts

代码语言:javascript
复制
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

代码语言:javascript
复制
<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上正确地呈现。

工作演示

如果你有任何疑问请告诉我。

注释:更新的ts代码

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71688233

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档