0

I am new to angular, I have created a service to loop the nested json data for my list.

export const CATEGORIES: Category[] = [
{
    id: 1,
    categoryName:'Accessories',
    subcatName: [
        {subcategory: 'belts',}
    ],
},
{
    id: 2,
    categoryName:'Clothing',
    subcatName: [
        {subcategory: 'jeans}',
    ],
},

];

and

@Injectable()
export class CategoriesService {

 constructor() { }

  getCategories(): Category[]{
    return CATEGORIES;
  }
}

I am trying to loop this data on my list

<ul>
    <li *ngFor="let cat of categoryList">
        <a href="#">{{cat.categoryName}}</a>
            <ul>
            <li *ngFor="let subcat of categoryList">
                <a href="#"> asdad {{subcat.subcategory}}</a>
            </li>
        </ul>
    </li>
</ul>

For this I have added code in component .ts file

 export class CategoriesComponent implements OnInit {

 categoryList: Category[];

 constructor(private categoryservice: CategoriesService) { }

 ngOnInit() {
   this.categoryList = this.categoryservice.getCategories();
 }

}

Please help, I want to create a navbar list of categories, when upon hover it shows the relevant subcategory. Please let me know if you need additional information.

2 Answers 2

1

in the inner loop, you should loop over the inner array

<ul>
    <li *ngFor="let cat of categoryList">
        <a href="#">{{cat.categoryName}}</a>
            <ul>
            <li *ngFor="let subcat of cat.subcatName">
                <a href="#"> asdad {{subcat.subcategory}}</a>
            </li>
        </ul>
    </li>
</ul>
Sign up to request clarification or add additional context in comments.

Comments

1

Your inner loop should iterate over cat of the parent not categoryList

Change

From

 <li *ngFor="let subcat of categoryList">
    <a href="#"> asdad {{subcat.subcategory}}</a>
 </li>

To

<li *ngFor="let subcat of cat.subcatName">
     <a href="#"> asdad {{subcat.subcategory}}</a>
</li>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.