This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Handling Click Events with Subjects

1:33 Angular 2 lesson by

While Angular 2 usually uses event handlers to manage events and RxJS typically uses Observable.fromEvent, a good practice when using Angular 2 and RxJS combined is to use Subjects and push the value through each event so that you can use it as part of your stream.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

While Angular 2 usually uses event handlers to manage events and RxJS typically uses Observable.fromEvent, a good practice when using Angular 2 and RxJS combined is to use Subjects and push the value through each event so that you can use it as part of your stream.

Avatar
Mike thompson

Slight aside here, but I noticed you experienced the same issue I was having with WebStorm auto-importing with double quotes instead of single quotes. Any way to have WebStorm auto-import with single quotes instead of double quotes?

To add a button to control our clock, I'll go ahead and create a button. I'll just say, "update." Typically, what you do in Angular 2 is say, "click" and then just give that a handler on click. Here, you'd create that on click handler.

Or from the other side, typically, what you do in our XJS is you'd say, "observable from event." Find the element, and then pass in the event name you want to listen to.

We have these two different conflicting approaches where we want to find an event, or we want to handle a click here. The way we're going to solve this for now is I'm going to delete this event handler. I'm going to delete this from event.

What I'm going to do is create something called a subject, which I'll call "click." This will be a new subject. I need to import subject. What this subject will allow me to do is call next every time I click.

What next is going to do is push the stream forward one tick. If I take out all of this clock stuff, which was just going every second before. Now I say this.clock is this.click.

I'm going to map those clicks to a new date. Hit save. I refresh over here. I'll click update. You can see we get our clock frozen in time at 44 seconds. I'll click update again. You can see that six seconds have passed.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?