Observable from <button> click event in Angular2

GBa picture GBa · Jun 12, 2016 · Viewed 40.7k times · Source

What's the preferred way to create an observable from a button's onclick event using Angular 2?

I'm not sure if it's considered best practice to grab the native element from the DOM in the component code (how do I do this?), or if there's some other shortcut I don't know about.

Answer

JoshuaDavid picture JoshuaDavid · Feb 15, 2017

Don't overthink it.

@ViewChild('button') button;
clicks$:Observable<any>;

ngOnInit() {
  this.clicks$ = Observable.fromEvent(this.button.nativeElement, 'click');
}