Angular 4 tree view


Using Angular, I’m trying to do a tree view listing something like a classified listing and I’m not sure how to go about displaying the sub category.

its easy displaying the parent category using the *ngfor directives but stuck as to how to display child category in Angular.

Looking for examples and ideas…the code i have is to display parent category and the code to display sub category is externally broken. With Angular I’m somewhat stuck as to how to loop inside a loop to display the information.

sample array:
categoryArray =
[{ “categoryId”: 1, “categoryName”: “Ford”, “subCategoryName”: “Mustang”, “year”: 1996 },
{ “categoryId”: 2, “categoryName”: “Honda”, “subCategoryName”: “Element”, “year”: 1997 },
{ “categoryId”: 3, “categoryName”: “GMC”, “subCategoryName”: “Suburban 2500”, “year”: 1994 },
{ “categoryId”: 4, “categoryName”: “Subaru”, “subCategoryName”: “Legacy”, “year”: 1992 },
{ “categoryId”: 6, “categoryName”: “Mercedes-Benz”, “subCategoryName”: “GLK-Class”, “year”: 2012 },
{ “categoryId”: 7, “categoryName”: “Honda”, “subCategoryName”: “Accord”, “year”: 1998 }]

the output should look like this:
example out put:
Honda Ford

  • Element - Car 1
  • Accord - Car 2
  • etc - etc

I think your best bet would be to transform the data to a more appropriate format first. You can reduce the array to a dictionary, where each key is the category name and the value an array of the items in that category;

const categoryDict = this.categoryArray.reduce((carry, current) => {
  const { categoryName } = current

  carry[categoryName] = carry[categoryName] || []

  return carry
}, {})

But since you can’t loop over object entries with *ngFor, you’ll have to convert it to an array containing the entries (or use a custom pipe):

this.categoryEntries = Object.entries(categoryDict)
  // This line is optional, just so that you don't have
  // to use numeric indices in the template:
  .map(([name, subCats]) => ({ name, subCats }))

Then you can display the data in the template like so:

  <li *ngFor="let cat of categoryEntries">
      <li *ngFor="let item of cat.subCats">
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.