You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular中渲染具有无限子级的嵌套数组的所有元素?

在Angular中渲染无限层级嵌套的分类数组

嘿,这种无限层级的嵌套结构,用Angular的递归组件来处理是最顺手的!本质就是让组件自己调用自己,完美适配任意深度的子级。我给你整理了完整的实现步骤:

1. 定义递归组件

先创建一个专门处理分类节点的组件,比如命名为CategoryTreeComponent。它只需要接收单个分类对象作为输入:

组件逻辑代码 (category-tree.component.ts)

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

// 复用你定义的类型
type categories = { name: string; sub?: categories[]; };

@Component({
  selector: 'app-category-tree',
  templateUrl: './category-tree.component.html',
  styleUrls: ['./category-tree.component.css']
})
export class CategoryTreeComponent {
  @Input() category!: categories;
}

2. 编写递归模板

在组件模板里,先渲染当前分类的名称,然后判断如果有sub子数组,就循环遍历每个子分类,再次调用当前组件(这就是递归的核心):

组件模板 (category-tree.component.html)

<div class="category-node">
  <!-- 渲染当前分类名称 -->
  <span>{{ category.name }}</span>
  
  <!-- 如果有子分类,递归渲染 -->
  <div *ngIf="category.sub && category.sub.length > 0" class="sub-categories">
    <app-category-tree 
      *ngFor="let subCat of category.sub" 
      [category]="subCat">
    </app-category-tree>
  </div>
</div>

3. 添加层级样式(可选但推荐)

为了让层级结构更直观,给不同层级的节点加个缩进:

组件样式 (category-tree.component.css)

.category-node {
  margin: 4px 0;
}

.sub-categories {
  margin-left: 20px;
  border-left: 1px solid #eee;
  padding-left: 8px;
}

4. 在父组件中使用

最后在你的父组件里,把根分类数组传给递归组件就行:

父组件模板示例

<div class="category-container">
  <app-category-tree 
    *ngFor="let rootCat of categories" 
    [category]="rootCat">
  </app-category-tree>
</div>

父组件逻辑里的分类数据

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

type categories = { name: string; sub?: categories[]; };

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html'
})
export class ParentComponent {
  categories: Array<categories> = [
    { 
      name: 'C1', 
      sub: [
        {name: 'S1'}, 
        {
          name: 'S2', 
          sub: [
            { 
              name: 'SS1', 
              sub: [
                { name: 'SSS1' }, 
                { name: 'SSS2' }
              ]
            }
          ]
        }
      ]
    }
  ];
}

这样不管你的分类有多少层级,组件都会自动递归渲染出来,完全不用担心深度限制~

内容的提问来源于stack exchange,提问作者Alecsandru Cristea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 18:09:05