angular - 递归模板超出调用堆栈的树
问题描述
使用这个要点,我可以毫无问题地显示一棵树..
我想以不同的方式对待第一级并像这样显示它:
我尝试了一些不同的变体,但我一直超出调用堆栈,例如 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)
解决方案
我决定稍微简化一下。
我创建了一个单独的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>
推荐阅读
- mysql - MySQL:在 SELECT IN 查询中使用 JSON_ARRAY 内容
- android - 移动设备自动选择对应的客户端证书
- javascript - 如何从带有 MongoDB 的游标中查找下一个 N 元素,没有 _id 并且在排序游标上
- vue.js - 未在实例上定义,但在渲染期间引用。确保此属性是反应性的,无论是在数据中
- java - 未找到 Java Maven 依赖项 (Stanford NLP)
- php - 为什么 flatten() 对这个集合没有任何影响 - Lumen/Laravel?
- ruby - 如何在 Ruby (v2.6.3) 中获取随机数
- sql - 使用 Oracle SQL 将重复计数连接到现有子查询
- c++ - Qt - QVector 和模型视图 - 从 listView 获取自定义类的最佳方法是什么?
- mysql - 查找限制删除的表+行