What's up with the strange event handling in Angular2?

How can a draggable vertical bar be created with Angular2? Setting isDragging to true when the user clicks it and calling moveHandler when the mouse moves seems straightforward, but there are a couple of issues:

  1. When the if-condition in ngOnInit is true, "dragging" is never printed.
  2. When the if-condition in ngOnInt is false, "dragging" is printed after the mouse is released.

Plunker Link

import {Component, OnInit} from '@angular/core';

@Component({
    selector: 'my-app',
    template: ` <div id="handler_vertical"  (mousedown)="startDragging()"></div> `
})
export class AppComponent implements OnInit {
    isDragging = false;
    width = 0;

    startDragging() {
        console.log("start dragging");
        this.isDragging = true;
    }

    dragHanlder(event: MouseEvent) {
        if (this.isDragging) {
            console.log("dragging");
            this.width -= event.movementX;
            // console.log("movementX:"+ event.movementX);
        }
    }

    stopDragging() {
        console.log("stop dragging");
        this.isDragging = false;
    }

    ngOnInit() {
        window.onmouseup = this.stopDragging;

        if(false){
            window.onmousemove = this.dragHanlder;            
        }else{
            window.onmousemove = (event) => {
                console.log("moving");
                this.dragHanlder(event);
            }
        }
    }
}

Answer №1

The issue lies in losing the context of the method when referencing it (specifically the "this" keyword) at this particular line:

window.onmousemove = this.dragHanlder; 

Using this approach, this will be pointing to Window:

dragHanlder(event: MouseEvent) {
  if (this.isDragging) { <== this === Window

To maintain the context of this, you can utilize arrow functions:

window.onmousemove = (e) => this.dragHanlder(e);

window.onmouseup = (e) => this.stopDragging(e);

Check out the updated plunker here.

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

Issue with Docker setup for managing a PNPM monorepo

As a newcomer to Docker, I am attempting to configure my fullstack API REST project. Within my PNPM workspace, I have two applications - a frontend built with Angular and a backend developed using AdonisJS. My goal is to create a Docker configuration for P ...

Is there an alternative to RequestOptionsArgs that I can use in this function?

I am currently working on updating an existing Angular application from version 4.3 to Angular 8. One of the challenges I'm facing is replacing old component classes like ConnectionBackend, RequestOptions, and RequestOptionsArgs with their updated equ ...

Typescript's Approach to Currying

In TypeScript, I am attempting to define types for a currying function. The implementation in JavaScript is shown below: function curry1(fn) { return (x) => (fn.length === 1 ? fn(x) : curry1(fn.bind(undefined, x))); } This function works effectively ...

Transform a flat 2D shape into a dynamic 3D projection using d3.js, then customize the height based on the specific value from ANG

Currently, I am utilizing d3.js version 6 to generate a 3D representation of the 2D chart shown below. Within this circle are numerous squares, each colored based on its assigned value. The intensity of the color increases with higher values. https://i.ss ...

unable to utilize a tip with d3 version 5 in a TypeScript environment?

i'm facing an issue with the following code snippet: var tip = d3.tip() .attr('class', 'd3-tip') .attr('id', 'tooltip') .html(function(d) { return d; }) .direction('n ...

Unexpected error encountered in Angular 2 beta: IE 10 displays 'Potentially unhandled rejection [3] SyntaxError: Expected'

Question regarding Angular 2 Beta: I am starting off with a general overview in the hopes that this issue is already recognized, and I simply overlooked something during my research. Initially, when Angular 2 Beta.0 was released, I managed to run a basic m ...

Guide on inserting a date into a MySQL DATETIME column in Angular with Node.js

In my application, I have a date picker component. My goal is to store the selected date in a MySQL database column with the data type of DATETIME. When using Angular, the value retrieved from the date picker is displayed as such: console.log(date.value): ...

Tips for showcasing an array containing two different types of objects in Angular

After sending a request to a remote server, I am returned with a JSON array. However, the array can contain two different types of JSON objects: [ { "country": "USA", "caseCount": 561, "caseDates": [], ...

How to arrange data in angular/typescript in either ascending or descending order based on object key

Hey there! I'm fairly new to Angular and have been working on developing a COVID-19 app using Angular. This app consists of two main components - the State component and the District component. The State component displays a table listing all states, ...

The function in Angular 2 is invoked a total of four times

Take a look at this example. This example is derived from an Angular quick start sample, where the template invokes a function. import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: `<h1>Hell ...

Is there a way to preselect the date in the input field as the default?

<mat-form-field> <input matInput [matDatepicker]="picker1" placeholder="From date: mm-dd-yyyy" name="from_date" [(ngModel)]="callListRequestOb.from_date" maxlength="150"> ...

Is it considered beneficial to use Observable as a static class member?

Lately, I have been diving into a new Angular project and noticed that the common way to share state between unrelated components is by using rxjs Subject/BehaviorSubject as static members within the class. For instance: export class AbcService { privat ...

The fusion of Typescript with Node.js

Currently, I am delving into learning typescript and exploring how to integrate it with Node.js. After watching multiple educational videos, I came across two distinct methods for linking typescript with Node.js. The first method involves using decorators, ...

core.js:15723 ERROR TypeError: Unable to access the 'OBJECT' property because it is undefined

Whenever I attempt to run this function, I encounter an issue. My goal is to retrieve the latitude and longitude of an address from Google's API. This error message pops up: core.js:15723 ERROR TypeError: Cannot read property 'geometry' of ...

What advantages could learning ReactJS first give me before diving into NextJS?

Just mastered TS and now faced with the decision of choosing a framework. I'm curious why it's recommended to learn ReactJS before NextJS. I've read countless articles advising this, but no one seems to delve into the reasons behind it. Ca ...

Module error caused by Typescript path inconsistency

After creating a new model named "project" within the existing project, I encountered an error when attempting to import the class into another typescript file in VS2019. The specific error message thrown is as follows: "ts2307 cannot find module ' ...

Establish the default landing page as the home screen when launching the application

Hey, I'm running into a situation where I need to change the default page of my application upon loading. Is there a way to redirect from the home page to another page when the application loads? Thanks! ...

What is the best way to create an Office Script autofill feature that automatically fills to the last row in Excel?

Having trouble setting up an Excel script to autofill a column only down to the final row of data, without extending further. Each table I use this script on has a different number of rows, so hardcoding the row range is not helpful. Is there a way to make ...

Tips for displaying multiple pages of a Power BI embed report on Mobile layout within the host application

I created a Power BI embed application using Angular on the frontend and C# on the backend. The issue I am facing is that when viewing Power BI reports in mobile layout, reports with multiple pages only show the default page and do not display the other pa ...

Issues with style not loading properly within innerHTML in Angular2

Currently, I am in the process of developing a page using Angular2/4 that includes a left navigation bar. To achieve reusability, I have separated this left menu into its own component and nested it within the main component. The objective is to utilize th ...