[英]Angular2 emit not working in child whilst using recursive component
我為正在開發的Angular2(Typescript)應用實現了類別的“樹”列表。 該組件應該使您能夠單擊類別名稱(無論是類別還是子類別),這將顯示該類別的產品。
我的“類別樹”組件是一個單獨的組件,因此可以遞歸使用,因此我可以正確地遍歷類別層次結構。 對於每個類別,將生成一個綁定了“ click”事件的跨度。 當我單擊時,我使用發射功能將該信息廣播回父組件,以便在那里更新一些變量。
此功能適用於頂級類別,但是當它位於子類別上時,單擊無法正常工作。 監視更改的功能不會收到任何信息。
這是我的代碼:
該功能將信息注銷到我的控制台中。 這是在父組件上:
changeCategory(event) {
console.log(event);
}
包含指令標記和發射事件名稱(categoryChange)的父代的html:
<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事件綁定到當前類別迭代的每個類別。 這將使用該信息在類別樹類中調用發射函數並將其廣播回去。 同樣,這適用於父類別,而不適用於子類別。
我的想法是,作為孩子的直接父組件,不是app.component.ts可能引起問題嗎? 我不確定。
有任何想法嗎?
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.