首页 > 解决方案 > 递归模板超出调用堆栈的树

问题描述

使用这个要点,我可以毫无问题地显示一棵树..

在此处输入图像描述

我想以不同的方式对待第一级并像这样显示它:

在此处输入图像描述

我尝试了一些不同的变体,但我一直超出调用堆栈,例如 ts 这里:

<h1>Angular 2 Recursive List</h1>
<ul>

    <li *ngFor="let item of list">
      {{item.title}} - LEVEL 0
      <ul *ngIf="item.children.length > 0">

        <ng-template #recursiveList let-list>
          <li *ngFor="let child of item.children">
            {{child.title}}
            <ul *ngIf="child.children.length > 0">
              <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: child.children }"></ng-container>
            </ul>
          </li>
        </ng-template>
        <ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: child }"></ng-container>


      </ul>
    </li>
</ul>

错误:

preview-d2335ca5bdb955611c1cb.js:1 ERROR RangeError: Maximum call stack size exceeded
    at NgForOf.ngDoCheck (ng_for_of.ts:212)
    at checkAndUpdateDirectiveInline (provider.ts:215)
    at checkAndUpdateNodeInline (view.ts:429)
    at checkAndUpdateNode (view.ts:389)
    at debugCheckAndUpdateNode (services.ts:431)
    at debugCheckDirectivesFn (services.ts:392)
    at Object.eval [as updateDirectives] (AppComponent.html:9)
    at Object.debugUpdateDirectives [as updateDirectives] (services.ts:386)
    at checkAndUpdateView (view.ts:359)
    at callViewAction (view.ts:615)

堆栈闪电战在这里

标签: angulartypescriptrecursiontree

解决方案


我决定稍微简化一下。

我创建了一个单独的list-item组件以便轻松发现错误。

列表项.component.ts

  @Input() title: string;
  @Input() children: any[];
  @Input('index') nestingLayer = 0;

列表项.component.html

<p [ngStyle]="{ 'margin-left': nestingLayer + 'rem' }">
  {{ title }}
</p>

<ng-container *ngIf="children.length">
  <app-list-item
    *ngFor="let item of children"
    [children]="item.children"
    [title]="item.title"
    [index]="nestingLayer + 1"
  ></app-list-item>
</ng-container>

最后,您的列表容器

<ul>
  <app-list-item 
    *ngFor="let item of list"
    [title]="item.title"
    [children]="item.children"
  ></app-list-item>
</ul>

StackBlitz 在这里


推荐阅读