问题
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 I need to display categories where parent_id is root
And on click for example on Dress category I need to show child categories (where parent_id is 1)
This is a table
<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
Thank You!
回答1:
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)
}
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>
来源:https://stackoverflow.com/questions/65069455/angular-display-categories-subcategories-in-table