Angular 在 ul 或 table 中显示类别和子类别
Angular display categories and subCategories in ul or table
我需要在 ul 或 [ 中显示我的 类别 =30=]table 和 单击 类别 我需要显示 子类别 ,但我不知道该怎么做。 ;(
<ul>
<li>category name</li>
</ul>
我需要从一个对象中做到这一点。
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"
}
]
因此,每次用户单击类别或子类别名称时,我都需要更改 ul 或 table 结构。
根类别是第一个显示类别。
如果它对我在我的项目中使用 ngx-datatables 有帮助。但是我可以使用默认的 tables。我只需要理解逻辑
谢谢!
使用*ngFor
迭代数组。
<ul>
<li *ngFor="let cat of cats">{{cat.category}}</li>
</ul>
创建一个列表(例如:filteredList)来存储要显示的数据。根据选择的类别更改filteredList的数据。
filteredList = [];
ngOnInit(){
this.filterByCategory('root')
}
filterByCategory(categoryId){
this.filteredList = this.cats.filter(cat => cat.parent_id == categoryId)
}
此处过滤函数将 return 满足条件的元素数组 ("cat.parent_id == categoryId")
现在更新模板以反映更改
<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>
我需要在 ul 或 [ 中显示我的 类别 =30=]table 和 单击 类别 我需要显示 子类别 ,但我不知道该怎么做。 ;(
<ul>
<li>category name</li>
</ul>
我需要从一个对象中做到这一点。
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"
}
]
因此,每次用户单击类别或子类别名称时,我都需要更改 ul 或 table 结构。
根类别是第一个显示类别。
如果它对我在我的项目中使用 ngx-datatables 有帮助。但是我可以使用默认的 tables。我只需要理解逻辑
谢谢!
使用*ngFor
迭代数组。
<ul>
<li *ngFor="let cat of cats">{{cat.category}}</li>
</ul>
创建一个列表(例如:filteredList)来存储要显示的数据。根据选择的类别更改filteredList的数据。
filteredList = [];
ngOnInit(){
this.filterByCategory('root')
}
filterByCategory(categoryId){
this.filteredList = this.cats.filter(cat => cat.parent_id == categoryId)
}
此处过滤函数将 return 满足条件的元素数组 ("cat.parent_id == categoryId")
现在更新模板以反映更改
<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>