【问题标题】:Iteration on Angular templateAngular模板上的迭代
【发布时间】:2022-01-19 01:32:25
【问题描述】:

我已经在一个 Angular 项目上工作了几个星期,我开始处理视图的数据。

但是,我开始使用从大 JSON 中提取的迭代,我尝试对其进行迭代,但无法正确完成。

我有这个 JSON

{
    "id": 1,
    "title": "App Komputer",
    "description": "Website dedicated to computer related products",
    "accessCode": "5128",
    "createdAt": "2022-01-13T21:19:11.000Z",
    "updatedAt": "2022-01-13T21:19:16.000Z",
    "sprints": [{
        "id": 1,
        "title": "Sprint 1",
        "releaseDate": "2022-01-20T21:37:13.000Z",
        "description": "Specs up to 01/22/2022",
        "createdAt": "2022-01-13T21:37:58.000Z",
        "updatedAt": "2021-12-13T01:46:36.000Z",
        "projectId": 1,
        "specifications": [{
            "id": 1,
            "title": "Add product button",
            "description": "New product button HTML",
            "duration": 10,
            "status": 1,
            "createdAt": "2021-12-23T01:46:36.000Z",
            "updatedAt": "2021-12-23T01:46:36.000Z",
            "sprintId": 1
        }]
    }]
}

我正在尝试迭代它,所以显示如下:

<div>
  <h1>{{ title }}</h1>
  <span>Access Code: {{ access_code }}</span>
    -- foreach sprints as sprint --
    <div>{{ sprint.title }}</div>
    -- foreach specifications as specification --
    <div>{{ specification.title }}</div>
    <span>{{ specification.description}}</span>
</div>

这是我的函数,我从中获取数据:

getProject(id: string): void {
    this.projectService.get(id)
      .subscribe({
        next: (data) => {
          this.currentProject = data; // currentProject is the JSON
          console.log(data);
        },
        error: (e) => console.error(e)
      });
  }

有人可以帮助我在我的 HTML 视图中完成所需的结果吗?如何遍历 JSON 数据?

非常感谢!

【问题讨论】:

    标签: arrays json angular loops view


    【解决方案1】:

    您可以使用*ngFor directive 遍历数组并显示项目数据。

    让我们假设变量 data 有你的 json 数据。在这种情况下,这就是您的 HTML 模板的样子。

    <h1>{{ title }}</h1>
    <span>Access Code: {{ data?.access_code }}</span>
    <div *ngFor="let sprint of data.sprints">
            <div>{{ sprint.title }}</div>
            <div *ngFor="let specification of sprint.specifications">
                <div>{{ specification.title }}</div>
                <span>{{ specification.description }}</span>
            </div>
     </div>
    

    【讨论】:

      猜你喜欢
      • 2018-09-02
      • 1970-01-01
      • 1970-01-01
      • 2011-07-01
      • 1970-01-01
      • 2021-02-05
      • 2016-11-20
      • 2013-06-06
      相关资源
      最近更新 更多