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.
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.
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.
A subscribe call is simply a way to start an "Observable execution" and deliver values or events to an Observer of that execution.
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.
Don't overthink it.
@ViewChild('button') button;
clicks$:Observable<any>;
ngOnInit() {
this.clicks$ = Observable.fromEvent(this.button.nativeElement, 'click');
}
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)">
@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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With