Angular – How to emit an event from parent to child

angulartypescript

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?

Best Answer

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.

Parent-Component

eventsSubject: Subject<void> = new Subject<void>();

emitEventToChild() {
  this.eventsSubject.next();
}

Parent-HTML

<child [events]="eventsSubject.asObservable()"> </child>    

Child-Component

private eventsSubscription: Subscription;

@Input() events: Observable<void>;

ngOnInit(){
  this.eventsSubscription = this.events.subscribe(() => doSomething());
}

ngOnDestroy() {
  this.eventsSubscription.unsubscribe();
}