我对此json层次结构(内容->类别->项目)有回应,内容包含类别的对象,每个类别包含项目的对象。所以我尝试了这个:
<div *ngFor="let content of data">
<span>{{content.name}}</span>
<div *ngFor="let category of content.categories">
<span>.....</span>
</div>
</div>
<div *ngFor="let item of category.items">
<span>{{item.type}}</span> //this item is undefined because it is out of category looping div
</div>
答案 0 :(得分:2)
*ngFor
对象的范围位于结束标记之内而不是结束标记之内,因此,可以使用 ng-template
您可以这样做
<ng-template let-content ngFor [ngForOf]="data">
<span>{{content.name}}</span>
<ng-template let-category ngFor [ngForOf]="content.categories">
<span>{{category.name}}</span>
<div *ngFor="let item of category.items">
<span>{{item.name}}</span>
</div>
</ng-template>
</ng-template>
和.ts
data = [{
categories: [{
name: 'xyz',
items: [{
name: 'item1'
}]
}]
}];
答案 1 :(得分:0)
将项目的for循环也放置在div中,循环遍历类别。如果您希望该div不在类别中,则还必须在其中进行更多循环。
<div *ngFor="let content of data">
<span>{{content.name}}</span>
<div *ngFor="let category of content.categories">
<span>.....</span>
<div *ngFor="let item of category.items">
<span>{{item.type}}</span> //this item is undefined because it is out of category looping div
</div>
</div>
</div>
其他循环之外的类别:
<div *ngFor="let content of data">
<span>{{content.name}}</span>
<div *ngFor="let category of content.categories">
<span>.....</span>
</div>
</div>
<div *ngFor="let content of data">
<div *ngFor="let category of content.categories">
<div *ngFor="let item of category.items">
<span>{{item.type}}</span>
</div>
</div>
</div>
答案 2 :(得分:0)
根据@Teun中的帖子评论,我认为你想要
<div *ngFor="let content of data">
<span>{{content.name}}</span>
<div *ngFor="let category of content.categories">
<span (click)="selectedCategory = category">.....</span>
</div>
</div>
<div *ngIf="selectedCategory !== undefined">
<div *ngFor="let item of selectedCategory">
<span>{{item.type}}</span>
</div>
</div>