我已经为我正在开发的Angular2(Typescript)应用程序实现了一个“树”类别列表 . 该组件应该允许您单击类别名称(无论它是类别还是子类别),这将显示该类别的产品 .
我的“category-tree”组件是一个单独的组件,它是递归使用的,因此我可以正确遍历类别层次结构 . 对于每个类别,生成一个范围,并将“click”事件绑定到该范围 . 单击时,我使用emit函数将此信息广播回父组件,以便更新那里的一些变量 .
此功能适用于顶级类别,但是当它位于子类别时,单击无法正常工作 . 监视更改的功能不会收到任何信息 .
这是我的代码:
将信息注销到我的控制台的功能 . 这是在父组件上:
changeCategory(event) {
console.log(event);
}
父类的html包含指令标记和emit事件名称(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>
子组件:
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
});
}
}
而递归组件html:
<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>
如您所见,我将click事件绑定到每个类别,即当前类别迭代 . 这将使用该信息调用category-tree类中的emit函数并将其广播回来 . 同样,这适用于父类别,但不适用于儿童 .
我的想法是,由于孩子的直接父组件不是app.component.ts,这可能会导致问题?我不确定 .
有任何想法吗?
谢谢
1 回答
这里的问题是emit只能直接与它的父组件对话 .
因此,我在这里找到了一个非常有用的问题和答案,它解释了服务事件以及如何使用如下服务与深层组件进行通信:
Global Events in Angular 2