问题描述
我有一个名为" ItemsComponent "的智能"组件,还有两个嵌套的哑巴"组件,分别为 ItemsListComponent 和 ItemComponent .
I have one "smart" component called ItemsComponent and two nested "dumb" components, ItemsListComponent and ItemComponent.
ItemsComponent 的html模板包含 ItemsListComponent .
ItemsComponent's html template contains ItemsListComponent.
// ItemsComponent
<div>
// ItemsListComponent
<app-items-list
[items]="items"
(doDelete)="deleteItem($event)"
>
</app-items-list>
<div>
,它具有一个名为 deleteItem 的功能:
and it has a function called deleteItem:
deletItem(item) {
// code to handle item deletion...
}
ItemsListComponent 包含 ItemComponent :
// ItemsListComponent
<ul *ngFor="let item of items">
// ItemComponent
<app-item
[item]="item"
(doDelete)="deleteItem($event)"
>
</app-item>
</ul>
所以html结构是这样的:
So the html structure is like this:
ItemsComponent (app-items)
- ItemsListComponent (app-items-list)
- ItemComponent (app-item)
ItemComponent 有一个按钮
<button (click)="deleteItem(item)">
和 deleteItem 的事件发射器:
@Output() doDelete = new EventEmitter();
deleteItem(item) {
this.doDelete.emit(item);
}
在 ItemComponent 中单击删除按钮时,事件只会冒出它的直接父对象 ItemsListComponent ,而不会成为 ItemsComponent ,除非我将相同的事件发射器功能添加到 ItemsListComponent .
When the delete button is clicked in ItemComponent, the event only bubbles up to it's immediate parent, ItemsListComponent, but doesn't make it to ItemsComponent unless I add identical event emitter functionality to the ItemsListComponent.
有臭味的 ItemsListComponent :
@Output() doDelete = new EventEmitter();
deleteItem(item) {
this.doDelete.emit(item);
}
以这种方式工作,但是 ItemsListComponent 现在与 ItemsComponent 共享代码味道,因为它们都具有相同的事件发射器内容,并且事件必须从一个组件传递到另一个正在上升.
It works this way, but ItemsListComponent now shares code smell with ItemsComponent since they both have the same event emitter stuff and the event has to be passed from one component to another on it's way up.
有更好的方法吗?
推荐答案
您已经意识到,自定义角度事件不会冒泡,因此,如果您的组件嵌套很深,并且希望将事件传递给更高的组件,介于两者之间的每个组件都必须向上委派事件.
As you've realised, custom angular events don't bubble, so if you have a deeply nested component and you want to pass an event to a higher component, every component in between has to delegate the event upwards.
另一种选择是将deleteItem
功能移至注入到您的较低级别组件之一中的服务.这样,可以在函数发生时调用该函数,而不必将事件冒泡到您的视图层次结构中.
Another option is to move your deleteItem
functionality to a service that is injected into one of your lower level components. That way, the function can be called at the point where it happens, rather than having to bubble the event up your view hierarchy.
这篇关于角度2:如何通过多个嵌套组件发出事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!