javascript - 如何以现代角度发出从孙子到祖父母的事件?
问题描述
如果我有多个级别的角度组件,我如何使用@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 可以深入钻取一些组件,实现此目的的最佳方法是什么,您能提供示例吗?
解决方案
可能有两种方式:
- 使用
@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在代码中已正确实现,因此可以继续使用。
- 使用
BehaviorSubject
viaService
:有了这么多层次的嵌套,你实际上可以创建一些类似的服务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
。
因此,应该做出相应的决定。
推荐阅读
- excel - 尝试刷新连接时出现 1004 错误
- java - 如何按 LatLng ArrayList 中值的顺序对 LatLng、String 的 Map 进行排序
- laravel - Laravel - 如何在存在依赖字段时防止删除
- python - 根据第 2 列中存在的字符串更新第 1 列
- python - 汇总 Pandas 中特定列上具有相同值的行
- java - 尝试在 Postgresql 数据库中保存对象失败(无异常)
- c# - 如何从字节数组制作精灵?
- swift - 在 Swift 中关闭键盘时,UIToolbar 不再显示在视图中
- javascript - 反应,将数据从 json 添加到单个帖子组件
- windows - 詹金斯没有在 Windows 上运行 sh 命令