Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Observable from <button> click event in Angular2

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.

like image 852
GBa Avatar asked Jun 12 '16 02:06

GBa


People also ask

Which of the following is the correct way to bind a click event to the button?

Bind the target event name within parentheses on the left of an equal sign, and event handler method or statement on the right. Above, (click) binds the button click event and onShow() statement calls the onShow() method of a component.

What is FromEvent in RxJs?

FromEvent: FromEvent is a method provided by RxJs to create Observable. The best thing is that we can create Observable from DOM events directly. By DOM events, it means click event, key up events, scroll events, etc.

Is subscribe Observable?

A subscribe call is simply a way to start an "Observable execution" and deliver values or events to an Observer of that execution.

What is Onclick in Angular?

Introduction to AngularJs onclick The ng-click directive can be used with multiple HTML elements such as button, input, select, checkbox, etc. This provides the developer ability to define custom behavior whenever an element is clicked.


3 Answers

Don't overthink it.

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

ngOnInit() {
  this.clicks$ = Observable.fromEvent(this.button.nativeElement, 'click');
}
like image 155
JoshuaDavid Avatar answered Nov 07 '22 12:11

JoshuaDavid


You can use Observable.fromEvent like explained in Angular2 RxJS getting 'Observable_1.Observable.fromEvent is not a function' error

Or just forward to an observable like

private obs = new Subject();
public obs$ = this.obs.asObservable();

@HostListener('click', ['$event']) 
clickHandler(event){
  this.obs.next(event);
}

or

<button (click)="obs.next($event)">
like image 20
Günter Zöchbauer Avatar answered Nov 07 '22 12:11

Günter Zöchbauer


@Gunter's example didn't quite work for me, because my compiler didn't recognize publ.

Here's an example of what worked for me: modal.component.ts

import { Output, Component } from '@angular/core';
import {Subject} from "rxjs/Subject";

export class MyModal{

    private clickStream = new Subject<Event>();

    @Output() observ = this.clickStream.asObservable();

    buttonClick(event:Event){
        this.clickStream.next(event);
    }
}

Inside modal.component.html:

<button type="button" class="btn btn-default" (click)="buttonClick($event)">click me</button>
like image 15
Jon Avatar answered Nov 07 '22 12:11

Jon