Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJS fromEvent operator with output EventEmitter in Angular

Tags:

angular

rxjs

Say there's ChildComponent which emits out an event called someEvent. Obviously, I can catch the event in ParentComponent declaring like, <child-component (someEvent)="onSomeEvent($event)"></child-component> and handle it with the method onSomeEvent in ParentComponent. But what I'm trying is that I want to handle the event with fromEvent operator in RxJS. I've tried fromEvent(this.childComponent.nativeElement, 'someEvent') after getting the ElementRef of the ChildComponent with @ViewChild. I discovered that the above approach works if the output EventEmitter's event name is the same as one of the native events such as click but it doesn't respond/work otherwise. Is there any ways to make it work with fromEvent?

like image 278
DongBin Kim Avatar asked Mar 12 '18 04:03

DongBin Kim


1 Answers

If you want to convert the event into an observable, you could use a Subject, like this:

@Component({
  selector: 'parent-component',
  template: `
    <child-component (someEvent)="subject.next($event)">
    </child-component>
  `
})
export class ParentComponent {
  public subject = new Subject<any>();
  constructor() {
    this.subject.pipe(
      tap(event => console.log(event)) // or whatever
    ).subscribe();
  }
}

Doing so will provide you with an observable source - the subject - that emits whatever value the event emitter emits. From that you can compose whatever you want using RxJS operators.

like image 69
cartant Avatar answered Oct 20 '22 11:10

cartant