【问题标题】:Angular2 emit not working in child whilst using recursive componentAngular2在使用递归组件时无法在孩子中工作
【发布时间】:2016-10-15 07:11:37
【问题描述】:

我已经为我正在开发的 Angular2 (Typescript) 应用程序实现了一个“树”类别列表。这个组件应该允许您能够点击一个类别名称(无论它是一个类别还是子类别),这将显示该类别的产品。

我的“类别树”组件是一个单独的组件,它以递归方式使用,因此我可以正确地遍历类别层次结构。对于每个类别,都会生成一个带有绑定到它的“点击”事件的跨度。单击后,我使用 emit 函数将此信息广播回父组件,以便在那里更新一些变量。

此功能适用于顶级类别,但点击子类别时无法正常工作。这 监视更改的函数不会收到任何信息。

这是我的代码:

将信息注销到我的控制台的功能。这是在父组件上:

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>

如您所见,我将单击事件绑定到每个类别,即当前类别迭代。这使用该信息调用类别树类中的发出函数并将其广播回来。这同样适用于父类别,但不适用于子类别。

我的想法是,作为孩子的直接父组件不是 app.component.ts 这可能会导致问题吗?我不确定。

有什么想法吗?

谢谢

【问题讨论】:

  • 如果我理解正确,您的 HTML 结构无效,因为您将 &lt;li&gt; 直接嵌套在另一个 &lt;li&gt; 下而没有包装 &lt;ul&gt;
  • 我认为您需要在public categoryChange:EventEmitter; 之前使用@Output,因此该组件将有一个事件(categoryChange),您将在该事件上添加处理程序changeCategory .. 我认为当您深入超过1 级时在组件中最好使用单例服务
  • 我已经修复了嵌套
      问题。感谢您指出这一点。原来的问题仍然存在。

标签: javascript typescript angular eventemitter


【解决方案1】:

这里的问题是,emit 只能直接与它的父组件对话。

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

Global Events in Angular 2

【讨论】:

  • 但这就是你正在做的。每个实例接收事件,然后将其传播到其直接父级。我认为这应该有效。上面提到的缺少的@Output() 加了吗?
猜你喜欢
  • 2017-04-03
  • 2016-07-02
  • 1970-01-01
  • 2017-07-19
  • 2017-09-10
  • 2019-10-17
  • 1970-01-01
  • 1970-01-01
  • 2018-06-14
相关资源
最近更新 更多