繁体   English   中英

使用递归组件时,Angular2发射在子级中不起作用

[英]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可能引起问题吗? 我不确定。

有任何想法吗?

谢谢

这里的问题是,发射只能直接与其父组件对话。

因此,我在这里找到了一个非常有用的问答,它解释了服务事件以及如何使用如下服务与深层组件进行通信:

Angular 2中的全球事件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM