如何将事件从父母传给孩子? [英] How to emit an event from parent to child?
本文介绍了如何将事件从父母传给孩子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我当前正在使用Angular2.通常,我们先使用@Output() addTab = new EventEmitter<any>();
然后使用addTab.emit()
向父组件发出事件.
I am currently using Angular 2. Usually we use @Output() addTab = new EventEmitter<any>();
and then addTab.emit()
to emit an event to parent component.
从父母到孩子,我们有什么方法可以做反之吗?
Is there any way we can do it vice cersa, from parent to child?
推荐答案
使用 RxJs ,您可以在父组件中声明Subject
并将其作为Observable
传递给子组件child组件只需要订阅此Observable
.
Using RxJs, you can declare a Subject
in your parent component and pass it as Observable
to child component, child component just need to subscribe to this Observable
.
父组件
eventsSubject: Subject<void> = new Subject<void>();
emitEventToChild() {
this.eventsSubject.next();
}
父母HTML
<child [events]="eventsSubject.asObservable()"> </child>
子组件
private eventsSubscription: Subscription;
@Input() events: Observable<void>;
ngOnInit(){
this.eventsSubscription = this.events.subscribe(() => doSomething());
}
ngOnDestroy() {
this.eventsSubscription.unsubscribe();
}
这篇关于如何将事件从父母传给孩子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文