网站搜索

typescript - 如何在 Angular 中逐个显示嵌套对象


我正在尝试显示嵌套对象以选择主对象或子对象来添加其他内容

const categories = [
  {
    id: 1,
    title: 'Tecnology',
    subCategory: [
      {
        id: 3,
        title: 'JavaScript',
        subCategory: [
          {
            id: 4,
            title: 'Angular',
          },
        ],
      },
      {
        id: 5,
        title: 'C#',
      },
    ],
  },
  {
    id: 2,
    title: 'Health',
  },
];

我的 HTML

<div>
  <a
    class="dropdown-item"
    *ngFor="let category of categories"
  >

    {{ category.title }}
    <span
      *ngFor="let subCategory of category.subForumCategories"
    >
      > {{ subCategory.title }}
    </span>
  </a>
</div>

预期结果

Tecnology
Tecnology > JavaScript
Tecnology > javaScript > Angualr
Tecnology > C#
Health

但是我得到了结果

Tecnology > javaScript > C#
Health

在 stackblitz: https://stackblitz.com/edit/angular-ivy-jfkszn?file=src/app/app.component.html

答案#1

可能最好在 TypeScript 中解决这个问题,然后迭代字符串数组而不是对象。Angular 模板在很多方面都很棒,但这可能已经开始超出它的适用范围了。

这是你可以在ts中拥有的示例

var categories = [{
    id: 1,
    title: "Technology",
    subCategory: [{
        id: 3,
        title: "JavaScript",
        subCategory: [{
          id: 4,
          title: "Angular"
        }]
      },
      {
        id: 4,
        title: "C#"
      }
    ]
  },
  {
    id: 2,
    title: "Health"
  }
];


getList();

function getList() {
  var list = extractSubCategories(categories);
  console.log(list);
}

function extractSubCategories(categories) {
  var list = [];
  for (var c of categories) {
    if (c.subCategory) {
      list.push(`> ${c.title}`);
      list.push(...extractSubCategories(c.subCategory).map(sc => `> ${c.title} ${sc}`));
    } else {
      list.push(`> ${c.title}`);
    }
  }
  return list;
}

模板:

<div>
  <a class="dropdown-item" *ngFor="let category of getList()" > {{category}} </a>
</div>

答案#2

你可以创建一个递归组件。然后你只需传入要显示的对象即可按你想要的方式显示。

组件.ts

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

@Component({
  selector: 'categories',
  template: `
     <div *ngFor="let category of categories">
        <div>
          {{titleHistory}} {{category.title}}
        </div>
        <categories[categories]="category.subCategory" 
                   [title]="titleHistory + category.title" 
                   [depth]="depth+1" 
                   *ngIf="category.subCategory"></categories>
    </div>`,
})
export class CommentComponent implements OnInit {
  @Input() categories: Categories;
  @Input() title: string = '';
  @Input() depth: number = 0;

  titleHistory = '';

  ngOnInit() {
    this.titleHistory = this.depth === 0 ? this.title : (this.title + ' > ');
  }
}

app.component.html

<categories [categories]="categoriesData"></categories>

stackblitz

编辑:已更新 Stackblitz,增加了更多选项