send event to child component angular 1

send event to child component angular

Parent-Component

eventsSubject: Subject = new Subject();

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


Parent-HTML

 


Child-Component

private eventsSubscription: Subscription;

@Input() events: Observable;

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

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

Here is what the above code is Doing:
1. The parent component creates a Subject and exposes it as an Observable via the asObservable operator.
2. The parent component passes the Subject as an input to the child component.
3. The child component subscribes to the Subject and does something when it receives a value.
4. The parent component calls next on the Subject to emit a value to the child component.

Similar Posts