Angular Display Categories & Subcategories in table

拥有回忆 提交于 2021-02-11 14:32:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!