Why are my variables resetting in Angular after ngAfterViewInit?

There seems to be an issue with my variables resetting after successfully using them in ngAfterViewInit().

I have a few @ViewChild and regular variables that are utilized or set in ngAfterViewInit. However, when certain events that I added post-initialization are triggered, these same variables appear as undefined.

Here is a slightly simplified version of the code:

// Variable declaration
@ViewChild('imagearea') imageArea: ElementRef;

dragBottomRight: HTMLElement;


ngAfterViewInit() {
    this.dragBottomRight = this.imageArea.nativeElement.querySelector('.br');

    this.imageArea.nativeElement.addEventListener("mousedown", this.dragStart);

    // The elements are logged correctly at this point
    console.log(this.imageArea, this.dragBottomRight);
}

dragStart(e: MouseEvent) {
    // This logs: undefined, undefined
    console.log(this.imageArea, this.dragBottomRight);
}

I've attempted setting the variables to static, and a similar code structure appears to work for my colleague.

Any assistance would be greatly appreciated.

Answer №1

It seems like the issue arises from not properly binding the function to the correct context.

To resolve this, you should modify:

this.element.addEventListener("click", this.handleClick.bind(this));

This change will ensure that the function maintains the same context, alternatively, you can also utilize arrow functions for a simpler solution.

Answer №2

Your event listener is using the incorrect context, make sure to use bind for the correct context or consider utilizing the Angular renderer to attach your event listener:

ngAfterViewInit() {
    this.dragHandle = this.imageArea.nativeElement.querySelector('.handle');
    this.dragStartListener = this.renderer.listen(this.dragHandle, 'mousedown', event => this.handleDragStart(event));
}

To remove the listener, simply call this.dragStartListener.

Remember: It's best practice to utilize Angular event bindings for attaching listeners, unless there are specific circumstances (like dynamically generated elements).

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

Identify the user's default character encoding in order to provide the appropriate CSV file

Is there a way for the website to automatically serve CSV files encoded as windows-1252 to users on Windows workstations, and encoded as UTF-8 to other users? Currently, two URL links are used which requires the user to decide which one to click. Most use ...

Why is the text not displaying in ReactJS when using Enzyme?

Can you please assist me in understanding why my test case is not running in React when using enzyme? I have installed enzyme js and followed this tutorial at Below is the code I am using: import React from 'react'; import Hello from './ ...

Capturing a part of the screen using JavaScript for screen recording

I'm exploring the possibility of implementing a JavaScript screen recorder that captures a video feed rather than the entire screen. I'm wondering if it's achievable using getDisplayMedia or if there's a specific library for this purpos ...

The Mantine date picker is causing an error stating that objects are not valid as a React child

I'm currently experimenting with utilizing Mantine Date in NextJS. The goal is to have the selected date displayed in the HTML text heading when a user clicks on it. For instance, if a user selects January 1st, 2023, the text should show like this: Da ...

Crystal-clear TextField component in Office UI Fabric

Seeking advice on how to clear a masked text field from Office UI Fabric using a button. Does anyone have a solution for this? I attempted to set the value using a state, but unfortunately, it did not work as expected. ...

@ngrx effects ensure switchmap does not stop on error

Throughout the sign up process, I make 3 http calls: signing up with an auth provider, creating an account within the API, and then logging in. If the signup with the auth provider fails (e.g. due to an existing account), the process still tries to create ...

Why are JavaScript errors constantly popping up when I use Django Pipeline?

After configuring Django Pipeline (version 1.3.15) for a specific group of JS files, I ensured they were in the correct order based on their appearance on my page. The collectstatic process went smoothly and when viewing the source, it looked like all th ...

Issue: Inability to scroll on div overflow section

My website consists of one static page with an HTML and CSS file. Oddly enough, when testing the page and inputting content into a multiline textarea until it overflows, the browser fails to display a scrollbar. Despite inspecting the div with the id &apos ...

Discovering time overlaps with Javascript and moment.js

In my calendar project, I am storing events for a day in an array. The start and end times are stored as String values in the following format: Example of events in a day const events = [{ "_id": "5bdf91a78197f0ced6c03496", "user": "5bd62237d6 ...

Angular is unable to fetch the chosen option from a dropdown selection

Recently, I encountered an issue with a module form that appears as a pop-up. Within this form, users can input data required to create a new object of a specific class. One field allows users to select a ventilation zone for the new room object being crea ...

Adjust Text to Perfectly Fit Button

I am developing a quiz using bootstrap and javascript. One issue I encountered is that the text in the buttons can sometimes be longer than the button itself. This results in the text not fitting properly within the button, making it unreadable on mobile ...

Hello there! I'm a beginner in React js and I was wondering if you could assist me in transforming this class component into

Hey there! I have the following code snippet and I'm looking to convert this class component to a functional component in React js. I'm new to React and could use some guidance on how to achieve this. My goal is to create a button that, when clic ...

What is the best way to update JSON data using JQuery?

I apologize for posing a seemingly simple query, but my understanding of JavaScript and JQuery is still in its early stages. The predicament I currently face involves retrieving JSON data from an external server where the information undergoes frequent ch ...

What is causing the malfunction with this JQuery/AJAX request?

Currently in the process of setting up an autocomplete feature. Following the guidance from php academy at the moment. My goal is to display "suggestions go here" below the input field whenever something is typed in. I have two files for this task: home.ph ...

The Rails text area fails to load through JavaScript when a line break is detected

My comment form has a feature that displays the content of the text area using js. It functions properly unless a new line is entered in the text area, in which case it does not show up right away. However, after refreshing the page, the comment appears wi ...

The usage of $('').switchClass in IE8 may cause an error when the switched class includes a color property

I have the following unique css classes .swap-format{ background-color: green; } .swap-format1{ background-color: orange; } .swap-format2{ color: purple; } Using these classes, I want to create an animation on the given div <div id="swap-clas ...

Problem with selecting items in Kendo UI Menu

Problem: The select event is not triggering when clicking on the image in the kendo menu item. My troubleshooting steps: Review the sample code provided below <!DOCTYPE html> <html> <head> <base href="http://demos.telerik.com/ken ...

Learn how to retrieve the HTTP headers of a request using AngularJS

When working with AngularJS, I know that accessing an HTTP request's GET parameters is easy using: $location.search().parameterOfInterest But how can I access the HTTP headers of the request? It's worth noting that I'm not utilizing $http ...

What is the Angular lifecycle event that occurs after all child components have been initialized?

Seeking help with implementing a concept for the following scenario: I have a parent search component containing several child components for displaying facets and search results. I want to automatically trigger a search once the application has finished ...

Consequences of eliminating Angular component wrapper tags from the DOM

Imagine there is a component named <hello-world> with the following HTML template: <div>Hello World!</div> When this component is used and inspected in the DOM, it shows up like this: <hello-world> <div>Hello World!</div ...