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

Angular模板递归中如何正确使用<parent>与<child>组件

可运行实现方案

1. 基础组件定义

parent 组件

parent.component.ts

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

@Component({
  selector: 'parent',
  template: `<ul>Parent: {{item.title}}</ul>`,
  standalone: true
})
export class ParentComponent {
  @Input() item!: Item;
}

child 组件

child.component.ts

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

@Component({
  selector: 'child',
  template: `<li>child: {{item.title}}</li>`,
  standalone: true
})
export class ChildComponent {
  @Input() item!: Item;
}

数据类型定义

types.ts

export interface Item {
  title: string;
  children?: Item[];
}

2. 递归模板实现(外层容器组件)

app.component.ts

import { Component } from '@angular/core';
import { Item } from './types';
import { ParentComponent } from './parent.component';
import { ChildComponent } from './child.component';
import { CommonModule } from '@angular/common';

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [CommonModule, ParentComponent, ChildComponent],
  template: `
  <div>
    <ng-template #recursiveList let-list>
      <span *ngFor="let item of list">
        <!-- 有子项的节点渲染parent + 递归子项 -->
        <ng-container *ngIf="item.children?.length; else noChildren">
          <parent [item]="item"></parent>
          <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: item.children }"></ng-container>
        </ng-container>
        <!-- 无子项的节点直接渲染child -->
        <ng-template #noChildren>
          <child [item]="item"></child>
        </ng-template>
      </span>
    </ng-template>

    <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: list }"></ng-container>
  </div>
  `
})
export class AppComponent {
  // 测试嵌套数据
  list: Item[] = [
    {
      title: '一级父节点',
      children: [
        { title: '子项1' },
        { title: '子项2' },
        {
          title: '二级父节点',
          children: [
            { title: '二级子项1' },
            { title: '二级子项2' }
          ]
        }
      ]
    }
  ]
}

3. 渲染效果验证

上述代码渲染后的DOM结构完全符合需求,二级父节点会自动嵌套生成对应的ul和子li,支持无限层级递归:

<div>
  <span>
    <ul>Parent: 一级父节点</ul>
    <span><li>child: 子项1</li></span>
    <span><li>child: 子项2</li></span>
    <span>
      <ul>Parent: 二级父节点</ul>
      <span><li>child: 二级子项1</li></span>
      <span><li>child: 二级子项2</li></span>
    </span>
  </span>
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 05:15:03