0

I have the following Array

categories = [{"id_product_cat":1,"category":"food","id_product_sub_cat":1,"subcategory":"Pizza"},{"id_product_cat":1,"category":"food","id_product_sub_cat":2,"subcategory":"Burger"},{"id_product_cat":1,"category":"food","id_product_sub_cat":3,"subcategory":"Chicken"},{"id_product_cat":1,"category":"food","id_product_sub_cat":4,"subcategory":"Sandwiches"},{"id_product_cat":2,"category":"drinks ","id_product_sub_cat":5,"subcategory":"Beer"},{"id_product_cat":2,"category":"drinks ","id_product_sub_cat":6,"subcategory":"Wine"},{"id_product_cat":2,"category":"drinks ","id_product_sub_cat":7,"subcategory":"Liquor"},{"id_product_cat":2,"category":"drinks ","id_product_sub_cat":8,"subcategory":"Water"},{"id_product_cat":2,"category":"drinks ","id_product_sub_cat":9,"subcategory":"Juice"}]

And I would like to loop through this preferably using a forEach() loop statement to reproduce the following in Angular. Category Name as heading then the respective sub-categories under each Category.

<div class="col-sm-12 vertical-menu">
 <h5>Categories</h5>
 <div class="vert-menu-list">
 <h6>Food</h6>
 <ul>
 <li><a routerLink="/">Burgers</a> </li>
 <li><a routerLink="/">Chicken</a></li>
 <li><a routerLink="/">Pizzas</a></li>
 <li><a routerLink="/">Sandwich</a></li>
 </ul>
 <h6>Drinks</h6>
 <ul>
 <li><a routerLink="/">Beer</a> </li>
 <li><a routerLink="/">Wine</a></li>
 <li><a routerLink="/">Liquor</a></li>
 <li><a routerLink="/">Water</a></li>
 <li><a routerLink="/">Juice</a></li>
 </ul>
 </div>
 
 </div> 
asked Sep 17, 2020 at 9:53
1
  • You could put them in <script> tags. Commented Sep 17, 2020 at 9:55

2 Answers 2

1

You can use ng-for, but before that you need to restructure the categories to have the following structure.

const categories = 
 [
 {
 category: "something", 
 subcategory: [
 {
 to:"somewhere", 
 label:"someString"
 }
 ]
 }
 ];
<div class="col-sm-12 vertical-menu">
 <h5>Categories</h5>
 <div class="vert-menu-list" *ngFor="category in categories">
 <h6>{{category.category}}</h6>
 <ul *ngIf="category.subcategory">
 <li *ngFor="subLink in category.subcategory">
 <a [routerLink]="subLink.to">
 {{subLink.label}}
 </a>
 </li>
 </ul>
 </div>
 </div> 
answered Sep 17, 2020 at 10:03
Sign up to request clarification or add additional context in comments.

Comments

0

You can do for loop in angular like this

<div *ngFor="let item of items; let myIndex = index>
 {{myIndex}}
</div>
answered Sep 17, 2020 at 10:01

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.