In my Angular2 (Typescript) app, I have integrated a 'tree' list of categories. This feature allows users to click on a category name, whether it's a main category or sub-category, and view the related products.
The 'category-tree' component is designed as a separate component and utilized recursively to navigate through the category hierarchy accurately. For each category, a span element is created with a 'click' event binding. Upon clicking, the emit function is triggered to send this data back to the parent component for updating certain variables.
Although this functionality works well for top-level categories, there is an issue with the click event not functioning correctly for child categories. The function responsible for monitoring changes does not receive any information in such cases.
Below is a snippet of the code:
Parent component's function capturing and logging information to the console:
changeCategory(event) {
console.log(event);
}
Parent component's HTML section hosting the directive tag and event name (categoryChange):
<div id='left-menu-wrapper'>
<div id='left-menu'>
<h1>{{title}}</h1>
<h2>Categories</h2>
<ul class="categories">
<category-tree [categories]="categories" (categoryChange)="changeCategory($event)"></category-tree>
</ul>
<div *ngIf="selectedCategory">
{{selectedCategory.name}}
</div>
</div>
<div *ngIf="!contentLoaded" class='spinner'></div>
</div>
<product-view [product]="selectedProduct"></product-view>
Child component:
import { Component, Input, Output, EventEmitter, forwardRef } from 'angular2/core';
@Component({
selector: 'category-tree',
templateUrl: './app/views/category-tree.html',
directives: [forwardRef(() => CategoryTree)],
outputs: ['categoryChange']
})
export class CategoryTree {
@Input() categories;
public categoryChange:EventEmitter;
constructor() {
this.categoryChange =new EventEmitter();
}
categoryClick(category) {
this.categoryChange.emit({
value: category
});
}
}
Recursive component HTML structure:
<li *ngFor="#category of categories">
<span (click)="categoryClick(category)" [class.selected]="category === selectedCategory">{{category.name}}</span>
<ul *ngIf="category.sub_categories" class='sub-category'>
<category-tree [categories]="category.sub_categories"></category-tree>
</ul>
</li>
While each category has a click event bound to it triggering the emit function with relevant details, this setup works smoothly for parent categories but faces challenges with child categories. It is suspected that the direct parent-child relationship may be impacting this behavior. Any insights on resolving this would be appreciated!
Thank you.