我必须显示书籍类别的分层树,但在呈现的 html 中没有数据。上下文似乎有问题ngTemplateOutput
。
尝试使用隐式和显式方法设置上下文。当明确设置时,例如let-list="list"
第一级类别列表被渲染,但子类别仍然没有。
角度版本:5.2.0
<div class="categories">
<div *ngFor="let rootCategory of categories">
<h1>{{rootCategory.name}}</h1>
<ul>
<ng-template #recursiveList let-list>
<li *ngFor="let subCategory of list">
<div>{{subCategory.name}}</div>
<ul *ngIf="subCategory.childCategories.length > 0">
<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: subCategory.childCategories }"></ng-container>
</ul>
</li>
</ng-template>
<ng-container *ngTemplateOutlet="recursiveList; context:{ $implicit: rootCategory.childCategories }"></ng-container>
</ul>
</div>
</div>
输出是:
<div _ngcontent-c5="" class="categories">
<!--bindings={
"ng-reflect-ng-for-of": "[object Object],[object Object"
}--><div _ngcontent-c5="">
<h1 _ngcontent-c5=""></h1>
<ul _ngcontent-c5="">
<!---->
<!--bindings={
"ng-reflect-ng-template-outlet-context": "[object Object]",
"ng-reflect-ng-template-outlet": "[object Object]"
}-->
<!--bindings={
"ng-reflect-ng-for-of": "[object Object],[object Object"
}--><li _ngcontent-c5="">
<div _ngcontent-c5=""></div>
<!---->
</li><li _ngcontent-c5="">
<div _ngcontent-c5=""></div>
<!---->
</li><li _ngcontent-c5="">
<div _ngcontent-c5=""></div>
<!---->
</li><li _ngcontent-c5="">
<div _ngcontent-c5=""></div>
<!---->
</li><li _ngcontent-c5="">
<div _ngcontent-c5=""></div>
<!---->
</li><li _ngcontent-c5="">
<div _ngcontent-c5=""></div>
<!---->
</li><li _ngcontent-c5="">
<div _ngcontent-c5=""></div>
<!---->
</li><li _ngcontent-c5="">
<div _ngcontent-c5=""></div>
<!---->
</li><li _ngcontent-c5="">
<div _ngcontent-c5=""></div>
<!---->
</li><li _ngcontent-c5="">
<div _ngcontent-c5=""></div>
<!---->
</li>
</ul>
</div><div _ngcontent-c5="">
<h1 _ngcontent-c5=""></h1>
<ul _ngcontent-c5="">
<!---->
<!---->
</ul>
</div><div _ngcontent-c5="">
<h1 _ngcontent-c5=""></h1>
<ul _ngcontent-c5="">
<!---->
<!---->
</ul>
</div><div _ngcontent-c5="">
<h1 _ngcontent-c5=""></h1>
<ul _ngcontent-c5="">
<!---->
<!---->
</ul>
</div><div _ngcontent-c5="">
<h1 _ngcontent-c5=""></h1>
<ul _ngcontent-c5="">
<!---->
<!---->
</ul>
</div>
</div>
没有显示类别数据。此外,此行的控制台出现错误:
<ul *ngIf="list.childCategories.length > 0">
错误:
ERROR TypeError: Cannot read property 'length' of undefined
at Object.eval [as updateDirectives]
简化的类别数组:
categories: Category[] = [
{
name: 'Category 1',
childCategories: [
{
name: 'Category 1.1',
childCategories: [
{
name: 'Category 1.1.1',
childCategories: [],
},
{
name: 'Category 1.1.2',
childCategories: [],
},
{
name: 'Category 1.1.3',
childCategories: [],
},
],
},
]
},
];