The issue with functions not executing when triggered by HammerJS

In my application, there is a component that displays information for different days as they are cycled through using the functions dayUp() and dayDown(). Here is an example of how these functions are structured:

  dayUp() {
    if (this.dayCount == 7) {
      return;
    }
    this.dayCount++;
    if (this.dayCount == 0) {
      this.today = 'Today'
    } else if (this.dayCount == 1) {
      this.today = 'Tomorrow'
    } else if (this.dayCount == -1) {
      this.today = 'Yesterday'
    } else {
      this.today = '';
    }
    this.getSelectedDay(this.dayCount);
  }

I have buttons set up to call these functions individually, and they successfully update the view with the new information. However, I am now trying to implement swipe functionality using HammerJS gestures. The swipes are being detected correctly in the correct directions, as confirmed by console logs. I have configured the swipe left gesture to trigger the dayDown() function and the swipe right gesture to trigger the dayUp() function. While the functions are being called properly during swiping, the view is not updating as expected. Strangely, the same functions work perfectly when triggered by the buttons. It's puzzling why the swipe gestures aren't producing the desired outcome. Below is the HammerJS code snippet:

    const switcher = document.getElementById('switcher');
    var mc = new hammer(switcher);
    mc.on('swipeleft', () => {
      console.log('left');
      this.dayDown();
    });
    mc.on('swiperight', () => {
      console.log('right');
      this.dayUp();
    });

Answer №1

Latest Update

If you encounter any issues, consider injecting ChangeDetectorRef and adding

this.changeDetectorRef.detectChanges()
in the callback functions following the execution of your custom functions.

private @ViewChild("myDiv") myBtn: ElementRef;

constructor(private changeDetectorRef: ChangeDetectorRef){}

myFunction() {
  const switcher = this.myBtn.nativeElement;
  var mc = new hammer(switcher);
  mc.on('swipeleft', () => {
    console.log('left');
    this.dayDown();
    this.changeDetectorRef.detectChanges()
  });
  mc.on('swiperight', () => {
    console.log('right');
    this.dayUp();
    this.changeDetectorRef.detectChanges()
  });
}

Previous Solution

To ensure proper functionality, execute the code within the ngZone as the variables are altered externally from Angular's scope due to being callbacks for Hammerjs APIs.

Moreover, it is advisable to utilize ViewChild to access DOM elements instead of direct methods such as getElementById or querySelector.

private @ViewChild("myDiv") myBtn: ElementRef;

constructor(private zone: NgZone){}

myFunction() {
  this.zone.run(_ => {
    const switcher = this.myBtn.nativeElement;
    var mc = new hammer(switcher);
    mc.on('swipeleft', () => {
      console.log('left');
      this.dayDown();
    });
    mc.on('swiperight', () => {
      console.log('right');
      this.dayUp();
    });
  });
}

For further insights, check out this tutorial:

Answer №2

To properly initialize, use new Hammer(switcher)(remember the capital 'H'). This is important for ensuring that all methods are able to access the object correctly.

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

Having trouble deserializing the POJO that was sent from an Angular HTTP post request within my Spring Boot POST-mapped function

My application is a coffee shop, and I am trying to send an array of items to my Spring Boot backend. However, Jackson is throwing an exception: Cannot construct instance of `me.andrewq.coffeeshop.menu_items.Menu` (no Creators, like default constructor, e ...

There seems to be a problem fetching the WordPress menus in TypeScript with React and Next

Recently I've started working on a project using React with TypeScript, but seems like I'm making some mistake. When trying to type the code, I encounter the error message: "TypeError: Cannot read property 'map' of undefined". import Re ...

Tips for displaying only the components associated with the user's role in Angular

Greetings everyone! I have a dashboard that features a menu showcasing all the components. I am looking to implement a functionality where, if logged in with the admin role, all components should be displayed. On the other hand, if logged in with the respo ...

Angular: Nested FormArray not populating the values in the FormControls

I have a form that contains a FormArray inside which you can dynamically add values and in this case I can retrieve the values using the FormControl. const formGroup = this._formBuilder.group({ dataArray: new UntypedFormArray([]), }); Inside this first ...

Setting a callback function as a prop for react-paginate in TypeScript: A step-by-step guide

When using react-paginate, there is a prop called onPageChange with the following type: onPageChange?(selectedItem: { selected: number }): void; After implementing it like this: const onPageChange = (selected): void => { console.log(selected); } ...

Retrieving data from an API using VUEJS3 and Typescript

I am facing an issue with displaying data in my template. When I try to do so, the screen remains blank. I am using Vue.js 3 with TypeScript and I am fairly new to this technology. <template> <div> <img :src="datas[0].imag ...

Error: Unable to cast value to an array due to validation failure

I'm currently working on integrating Typegoose with GrqphQL, MongoDB, and Nest.js for a project. My goal is to create a mutation that will allow users to create a post. I have set up the model, service, and resolver for a simple Post. However, when I ...

Firebase data not appearing on screen despite using the async pipe for observables

My current challenge involves accessing data based on an id from Firebase, which comes back as an observable. Upon logging it to the console, I can confirm that the Observable is present. However, the issue arises when attempting to display this data on th ...

Angular 2 components not properly handling two-way binding errors

Exploring how to achieve two-way binding in Angular 2, I am currently working with the following parent component setup: app.component.html: <child [(text)]="childText" (textChanged)="textChanged($event)"></child> <span>{{childText}}< ...

Navigating Errors within Express Class Using Typescript

I encountered an issue while transforming my Express.js application into a Typescript class, specifically with error handling. Below is the content of my App.ts class file: import express from 'express'; import compression from 'compression& ...

Oops! There seems to be an issue with locating a differ that supports the object '[object Object]' of type 'object', like an Array

I'm currently encountering an error that reads: (ERROR Error: NG02200: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables, such as Arrays. Did you mean to use the key ...

Error in TypeScript code for combined Slider and Input onChange functionality within a Material-UI component

HandleChange function is used to update the useState for Material-UI <Slider /> and <Input />. Here is the solution: const handleChange = (event: Event, newValue: number | number[]) => { const inputValue = (event.target as HTMLInputEle ...

The 'ref' attribute is not found within the 'IntrinsicAttributes' type

I'm currently working on a TypeScript project using React. Although the code is functional, I keep encountering compiler errors with my ref. Here's an example of the code: Firstly, there's a higher-order component that handles errors: expor ...

Storing dates using Angular 2 and JSON for efficient data management

I've encountered a challenging issue with my Angular 2 application. I'm attempting to organize my API (MongoDB) in such a way that each new "post" added by the admin can be retrieved by date (not time) on the front end. Here's an example of ...

Broaden the natural interface for the element

I'm looking to create a uniquely customized button in React using TypeScript. Essentially, I want to build upon the existing properties of the <button> tag. Below is a simplified version of what I have so far: export default class Button extend ...

Using `publishReplay()` and `refCount()` in Angular does not behave as anticipated when dealing with subscriptions across multiple components

I am currently investigating the functionality of publishReplay in rxjs. I have encountered an example where it behaves as expected: const source = new Subject() const sourceWrapper = source.pipe( publishReplay(1), refCount() ) const subscribeTest1 = ...

Interact with DOM elements and manipulate TypeScript data

I am looking to display a list of IDs by fetching them from my database. Within my ngfor loop, I have included a child component. Is there a way to access each ID within each child component? I would like to retrieve the value of "GameToDisplay.key" in pl ...

What is the most effective way to retrieve data from a URL and process it using reactjs?

Looking to consume JSON data from a URL, here is an example of the JSON structure: { "results": [ ... ], "info": { ... } } I aim to display the fetched data as a component property. What is the most efficient way to achie ...

Separate the label and content sections in an Angular Material vertical stepper

After applying the following CSS: mat-step-header{ display: flex ; justify-content: flex-end ; } I am attempting to make this stepper function properly. I have implemented Angular Material design for a vertical stepper. How can I position the steppe ...

Mobile Safari on iOS devices is known for its capability to overlay HTML5 <video> on top of everything

Although a similar question was asked 6 years ago without any answers, I am currently facing the same issue. Problem: The <video> tag in my Angular/Ionic application overlaps my image and two buttons in iOS Mobile Safari - no matter what I try! It ...