角度显示类别和表中的子类别 [英] Angular Display Categories & Subcategories in table
问题描述
我需要在表格中显示类别和子类别.
I need to display my categories and subcategories in the table.
所以我有带有类别的对象
So I have object with categories
cats = [
{
"id": "1",
"parent_id": 'root',
"category": "Dress"
},
{
"id": "17",
"parent_id": "1",
"category": "Dress 2"
},
{
"id": "19",
"parent_id": "1",
"category": "Men"
},
{
"id": "30",
"parent_id": "19",
"category": "Shorts 2"
},
{
"id": "31",
"parent_id": "19",
"category": "Shorts"
}
]
OnInit我需要显示 parent_id 是 root
OnInit I need to display categories where parent_id is root
然后单击例如连衣裙类别我需要显示子类别(其中 parent_id为1 )
And on click for example on Dress category I need to show child categories (where parent_id is 1)
这是一张桌子
<div class="row">
<div class="col-md-12">
<table class="bootstrap table-striped">
<tr>
<th>Category Name</th>
</tr>
<tr *ngFor="let cat of cats">
<td>
<a>{{ cat.category }}</a>
</td>
</tr>
</table>
</div>
</div>
我需要使用什么?也许一些过滤器?我不知道,什么也没找到
What I need to use? maybe some filter? I don't have idea and I didn't find anything
谢谢!
推荐答案
创建一个列表(例如:filteredList)以存储要显示的数据.根据所选类别更改filteredList的数据.
Create a list(eg: filteredList) to store the data to be shown. Change the data of the filteredList according to the category selected.
filteredList = [];
ngOnInit(){
this.filterByCategory('root')
}
filterByCategory(categoryId){
this.filteredList = this.cats.filter(cat => cat.parent_id == categoryId)
}
此处过滤器函数将返回满足条件的元素数组("cat.parent_id == categoryId")
Here the filter function will return an array of elements which will satisfy the condition ("cat.parent_id == categoryId")
现在更新模板以反映更改
Now update the template to reflect the changes
<div class="row">
<div class="col-md-12">
<table class="bootstrap table-striped">
<tr>
<th>Category Name</th>
</tr>
<tr *ngFor="let cat of filteredList">
<td>
<a (click)="filterByCategory(cat.id)">{{ cat.category }}</a>
</td>
</tr>
</table>
</div>
</div>
这篇关于角度显示类别和表中的子类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!