What is the procedure for obtaining an Observable for an Event?

How can I obtain an Observable of an Event in Angular 2?

For instance, is it possible to subscribe to a click event but only trigger after two clicks? Can we create an Observable of MouseClick event objects?

If I want to filter by button or ctrlKey, or have an Observable of KeyboardEvent and filter by key \ keyCode, or any potential future scenarios?

I came across which mentioned the property valueChanges as Observable<string>.

In addition, on https://github.com/angular/angular/issues/5489, there was a method demonstrated as follows:

this.clickStream = new Subject();
...
<button (click)="clickStream.next($event)">Click Me</button>

Is using the Subject method shown above the correct approach? I am uncertain.

While I lack experience with Angular 2 and RxJS, I am interested in both and exploring them for potential use in upcoming projects.

Edit

Here's my Plunker showcasing a simple click use case http://plnkr.co/edit/u1A7ve2fAYigjwaZ0x1v?p=preview

Answer №1

When working with Observables, you can use the fromEvent operator provided in RxJS, but first, you will need a reference to the native element. To obtain this reference, you can utilize viewChild or contentChild to access an elementRef.

To bind to the click event of the element, you can create a stream like this:

var clickStream = Observable.fromEvent(btnRef.nativeElement, 'click');

If your goal is to only emit events after two consecutive clicks (or once for every 2 clicks), you can achieve this using the bufferWithCount operator:

var triggerFor2Clicks = clickStream.bufferWithCount(2);

This will produce an array of 2 events at a time, enabling you to handle actions accordingly:

triggerFor2Clicks.subscribe(() => my2ClicksHandler);

It's worth noting that the argument in the subscribe function is empty ('()'), indicating that you are interested in the count of events rather than the specific event data.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble with AJAX request on iPad, works perfectly on desktop

Here is some of my custom plugin code (function ($) { $.fn.createGallery = function(options) { var theObject = $(this); var settings = $.extend({ // Default settings. server: 'http://localhost/jQuery%20Gall ...

I'm looking to create a unique combination of a line and bar chart. Any advice on how to

When I stretch my Scale like this determineDataLimits: function () { var min = Math.min.apply(null, this.chart.data.datasets[0].data) console.log(this) console.log(defaultConfigObject) Chart.options.scales.rightSide.ticks.min = function ...

The issue with fetching user profile data on the client-side in Next.js 14

I've run into a problem with client-side data fetching on my Next.js 14 project. More specifically, I'm trying to retrieve user profile information from a backend API using Axios within a component, but for some reason, the data isn't coming ...

What is the proper way to include a URL when submitting an AJAX form?

When I try to call a servlet using HTML, jQuery and Ajax by submitting a form, I keep getting a 404 error saying the resource cannot be found. My project is built with Maven. The Servlet is located in the src/main/java package under : com.mycompany.sample ...

The format of the date cannot be modified when using DesktopDatePicker as a React Component

I've been attempting to modify the appearance of the component, but the UI keeps showing the date in month-year format. <DesktopDatePicker inputVariant="outlined" label="Pick-up date" id="date ...

Countdown to redirect or exit on Jquery mobile "pageshow" and "pagehide" events

Looking to implement a 30-second countdown on a Jquery Mobile page with specific requirements: (1) Countdown begins on pageshow (2) Redirects to new page when countdown expires (3) If user navigates away (pagehide) before countdown finishes, the timer fun ...

Trie-based autocomplete functionality

I am currently creating an auto-completion script and I'm considering utilizing a trie data structure. My main concern is that I want all possible matches to be returned. For instance, when I type in the letter r, I expect to see all entries beginning ...

The challenge of transferring documents to the server

There is a form on the webpage where users can select a file and click a button to send it. <form enctype="multipart/form-data"> <input type="file" id="fileInput" /> <button type="button&quo ...

Could anyone explain why this basic angularjs jsfiddle isn't functioning properly?

Could someone explain why this basic angularjs jsfiddle isn't functioning? var myApp = angular.module('myApp',[]); myApp.controller('MyCtrl', ['$scope', function MyCtrl($scope) { $scope.name = 'Superhero'; ...

How can I retrieve the value of a specific <span> element by referencing the class of another <span> within

I have come across the following HTML: <div class="calculator-section"> <p> <span class="x"></span> <span class="amount">30</span> </p> <p> <span class="y"></span ...

Identify the geometric figure sketched on the canvas using the coordinates stored in an array

After capturing the startX, startY, endX, and endY mouse coordinates, I use them to draw three shapes (a line, ellipse, and rectangle) on a canvas. I then store these coordinates in an array for each shape drawn and redraw them on a cleared canvas. The cha ...

How can I showcase data retrieved from a function using Ajax Datatable?

I have implemented an Ajax function that retrieves data from a PHP file and displays it in a DataTable. Initially, this setup was working fine. However, when I added a new function to the PHP file, my Ajax function stopped retrieving data from the file. I ...

Using Vuex to calculate the percentage of values within an array of objects and dynamically updating this value in a component

I'm currently in the process of developing a voting application with Vuex. Within the app, there are buttons for each dog that users can vote for. I have successfully implemented functionality to update the vote count by clicking on the buttons: sto ...

X-ray Picker failing to retrieve a value

I am currently using the most recent version of the x-ray npm module in the code snippet below. Despite my expectations, the Meta and Metatags elements remain empty when I print out obj. Can anyone help me identify what I might be missing? var Xray = req ...

changing the core JavaScript of a keyboard plugin

To access the demo, click on this link: . You can find the main javascript file at https://raw.githubusercontent.com/Mottie/Keyboard/master/js/jquery.keyboard.js. Is there a way to switch the positions of the accept and cancel buttons? ...

Unveiling the solution: Hide selected options in the input field of Material UI Autocomplete in React

I need help with not displaying the labels of selected options in the input field. I think it might be possible to do this using the renderInput property, but I'm not sure how. Even with the limitTags prop, the options still show up in the input field ...

Top tip for receiving a JSON response object using AngularJS

I am currently working with an API that returns a json array object. In my Controller, I have been able to retrieve the json data successfully using the following code: angular.module('lyricsApp', []) .controller('LyricsController', [& ...

How to anticipate an error being thrown by an observable in RxJS

Within my TypeScript application, there exists a method that produces an rxjs Observable. Under certain conditions, this method may use the throwError function: import { throwError } from 'rxjs'; // ... getSomeData(inputValue): Observable<s ...

Utilize the clearChart() function within Google charts in conjunction with vue-google-charts

I have integrated vue-google-charts to display various charts on my website. I want to allow users to compare different data sets, by enabling them to add or delete data from the chart. In order to achieve this functionality, I need to find a way to clear ...

Replacing text within a paragraph using D3.js

Is it possible to develop a D3 function that can choose a paragraph, delete its content, and replace it with new text? If so, what would be the most effective way to accomplish this? I attempted the following: d3.select("#triggerButton") .on("clic ...