首页 > 解决方案 > 如何以现代角度发出从孙子到祖父母的事件?

问题描述

如果我有多个级别的角度组件,我如何使用@Output从孩子向祖父母发出事件?

祖父母:

<parent (handleClick)="grandmaHandleClick($event)">
<parent>
...
grandmaHandleClick(event) {
  console.log('grandma knows you clicked')
}

家长:

<child (handleClick)="handleClick($event)">
</child>

孩子:

<div (click)="onClick()">Click button
</div>
...
@Output() handleClick = new EventEmitter
onClick() {
  this.handleClick.emit('clicked a button')
}

我正在尝试使用它,以便@Output 可以深入钻取一些组件,实现此目的的最佳方法是什么,您能提供示例吗?

标签: javascriptangulartypescriptevents

解决方案


可能有两种方式:

  1. 使用@output

祖父母

<parent (notifyGrandParent)="grandmaHandleClick($event)">
<parent>
...
grandmaHandleClick(event) {
  console.log('grandma knows you clicked')
}

家长

<child (handleClick)="childEvent($event)">
</child>

@Output() notifyGrandParent= new EventEmitter();
childEvent(event) {
  this.notifyGrandParent.emit('event')
}

Child在代码中已正确实现,因此可以继续使用。

  1. 使用BehaviorSubjectvia Service:有了这么多层次的嵌套,你实际上可以创建一些类似的服务EventService,然后创建BehaviorSubject可以直接被 GrandParent 订阅的服务。此外,为了使这个service组件更加具体,您可以将此服务保留在一个module包含其他 3 个组件(GrandParent、Parent 和 Child)中
export class EventService{

 private childClickedEvent = new BehaviorSubject<string>('');

  emitChildEvent(msg: string){
     this.childClickedEvent.next(msg)
  }

  childEventListner(){
     return this.childClickedEvent.asObservable();
   } 

}

然后在components

子组件

export class ChildComponent{
   constructor(private evtSvc: EventService){}

   onClick(){
     this.evtSvc.emitChildEvent('clicked a button')
   }
}

祖父母

export class GrandComponent{
   constructor(private evtSvc: EventService){}

   ngOnInit(){
     this.evtSvc.childEventListner().subscribe(info =>{
         console.log(info); // here you get the message from Child component
      })
   }
}

请注意,通过@output事件,您创建了组件的紧密耦合,因此创建了强依赖关系(父子孙子)。如果组件不可重用并且只是为了达到这个目的而创建的,那么@output也是有意义的,因为它将向任何新开发人员传达他们具有父子关系的消息。

创建一个传递数据的服务也会将数据暴露给其他可以注入service的组件constructor

因此,应该做出相应的决定


推荐阅读