Can an event in Angular be used to exit a loop?

I'm trying to figure out how to create a function that will continue running until a specific event, such as mousemove or mouseup, occurs. Here's an example of what I have in mind:

@HostListener('window:mousedown', ['$event'])
onMouseDown(): void {
    while (true) {
        // do stuff
        if(mouseUpEvent || mouseMoveEvent) { // <-- how can I stop the loop when either mouseUp or mouseMove happens?
            return;
        }
    }
}
@HostListener('window:mouseup', ['$event'])
onMouseUp() : void {
    // do stuff
}
@HostListener('window:mousemove', ['$event'])
onMouseMove() : void {
    // do stuff
}

Answer №1

To utilize Observables for this task, you can keep track of mouse events by updating specific BehaviorSubjects. By listening to changes in these subjects, you can create a chain of events using rxjs to enhance event handling.

mouseDown$ = new BehaviorSubject<void>();
mouseUp$ = new BehaviorSubject<void>();
mouseMove$ = new BehaviorSubject<void>(),

listenToMouseEvents(): void {
  this.mouseDown$.pipe(
    takeUntil(merge(this.mouseUp$, this.mouseMove$)),  
    repeat()  
  ).subscribe(() => {
     // perform desired actions
  })
}

@HostListener('window:mousedown', ['$event'])
onMouseDown(): void {
  this.mouseDown$.next();
}
@HostListener('window:mouseup', ['$event'])
onMouseUp() : void {
  this.mouseUp$.next();
}
@HostListener('window:mousemove', ['$event'])
onMouseMove() : void {
  this.mouseMove$.next();
}

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

encountering a loading issue with angular2-modal in rc1 version

Currently, I am implementing a library called angular2-modal. This library offers various modal options including bootstrap and vex for angular 2. While vex is functioning properly, I encounter an error when switching to bootstrap: responsive-applicati ...

Transferring information between views using AngularJS within the same controller

Issue Overview : I am facing a challenge with my angular application. I have a form on one view (first) that redirects the user to another view (second) upon successful submission via an AJAX call. The entire application is managed by a single controller, ...

Working with AngularJS $resource: including an array element in paramDefaults

I'm currently working with the twitch.tv API and utilizing the Angular $resource factory. My goal is to access the endpoint: GET /channels/:channel. What I want to achieve is to retrieve the channel for each element within an array. I attempted using ...

Steps for displaying a two-dimensional dataset in a tabular format

My dataset includes column names, row names, and values for specific row/column combinations. Here is a glimpse at the structure: cols = ['A', 'B', 'C', 'D']; rows = ['1', '2', '3', &ap ...

After changing routes in Angular 4, the application experiences decreased speed and a continual increase in the number of nodes, particularly noticeable in Chrome but not in Firefox

After switching routes multiple times, I noticed a decrease in the app's speed. Upon inspecting the 'performance + memory' section using Chrome debugger, I observed an increasing number of DOM nodes. It seems that the DOM nodes are not prop ...

Is it advisable to pass useSelector to useState in React?

Hey everyone, I've got a question about preferences for a specific method: When working with a React functional component in TypeScript that retrieves values from Redux State using useSelector, which approach do you prefer? 1) const campaign = us ...

Exploring the power of Angular CLI and webpack

Exploring the capabilities of angular cli https://github.com/angular/angular-cli#documentation After creating a basic app, I can easily access it on localhost. Upon inspecting the localhost site, I notice the css and js links that are added by webpack. ...

Can ngTemplateOutletInjector be utilized to enable NgModel functionality within a nested template enclosed by a form? What are the prerequisites for NgModel to function properly?

With the release of angular 14, the ngTemplateOutlet directive now includes a new parameter: ngTemplateOutletInjector. According to the angular documentation, this parameter specifies an "injector to be used within the embedded view." Prior to this update ...

Exploring the power of AngularJS through JSON with multidimensional arrays

My goal is to construct a multidimensional array capable of storing 6 JSON responses. To seek guidance, I have consulted other resources such as this thread on multidimensional arrays in Angular. However, upon testing my console log for the multidimension ...

The term 'Pick' is typically used to identify a specific type, however, in this particular situation, it appears to be functioning as a value while attempting to expand the Pick

I'm attempting to selectively expose certain properties from an ancestor class on my descendant class. My approach involves using the Pick utility in TypeScript. export class Base { public a; public b; public c; } export class PartialDes ...

Instructions for inserting a hyperlink into a column of a table with the *ngFor directive in Angular2

I currently have a table with 4 columns: Name, ID, Department, and City. I am fetching both the row data and column data as an array from a TypeScript file and iterating through them using *ngFor. Below is a snippet of my code: <tbody> <tr *ng ...

Issues with the linear-gradient feature in Ionic3 are preventing it from properly functioning

I'm currently experimenting with creating a unique gradient color in my Ionic3 variable.sass file. $colors: ( primary: #4471C1, secondary: #32db64, danger: #f53d3d, light: #f4f4f4, dark: #222, newcolor: linear-gradient( ...

Encountering a problem when launching the "vite-express" template on the Remix app (TSConfckParseError: error resolving "extends")

I recently launched a brand-new [email protected] project using the remix-run/remix/templates/vite-express template after executing this command: npx create-remix@latest --template remix-run/remix/templates/vite-express However, upon trying to run th ...

Restrict the number of items in a list in Angular 2 to a

I need help structuring a list of material cards in my application. The list can potentially have a large number of elements, so I want to limit it to showing only 5 items at a time and provide an option for the user to navigate through additional elements ...

"Exploring the world of child components in Angular

I am looking to create a unique component structure with the following syntax: <my-component [attr1]="attr1" [attr2]="attr2"> </my-component> While the basic structure is good, I need the flexibility to render different types of templates wit ...

AngularJS directive error: Incorrect function invoked

I have two similar scenarios where I need to apply validators for specific files, even though I am aware that this goes against the DRY principle. However, being new to AngularJS, I am still learning the ropes. module.js var $moduleExample = angular.modu ...

Incorporate Angular application with SAML protocol

Greetings! I am a beginner in both Angular and SAML. I have recently embarked on creating an Angular 6 application and now I am looking to integrate this application with SAML for implementing a login module using VIDM. However, I am unsure of how to go ...

Unable to compile TypeScript files using gulp while targeting ES5

After starting my first Angular2 app, I encountered an issue where I couldn't use gulp to compile for es5. Below is the dependencies file: "dependencies": { "@angular/common": "2.0.0", "@angular/compiler": "2.0.0", "@angular/compiler-cli ...

Angular's $http.get method allows you to make HTTP

My goal is to display all lists and the tasks associated with each list. In my controller, I have the following code: $http.get('api/list/').success(function (data) { $scope.lists = data; $scope.tasks = data[0].Task; ...

Encountering difficulties during the installation of Angular 6.0.8

We encountered an error during the Angular installation process which resulted in Angular not being installed correctly. D:\software\node-v8.11.2-win-x64>npm install -g @angular/cli D:\software\node-v8.11.2-win-x64\ng -> ...