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

What is the process for downloading a .docx file encoded in Base64?

Trying to download a .docx file received from the backend. The object being received is shown below: Download attempt using the following code: const blob = new Blob([fileSource.FileData], { type: fileSource.FileType }); FileSaver.saveAs(blob, (fileSour ...

How to handle an already initialised array in Angular?

I came across an interesting demo on exporting data to Excel using Angular 12. The demo can be found at the following link: This particular example utilizes an array within the component TypeScript file. import { Component } from '@angular/core' ...

Resolve the problem in Angular 6 related to an unused type and the absence of a certain property

I recently watched a video tutorial (link: https://www.youtube.com/watch?v=z4JUm0Bq9AM) and encountered some errors in my CLI. The specific errors are as follows: ERROR in sidebar.component.ts(12,5): error TS7028: Unused label. sidebar.component.ts(14,56 ...

What sets apart the states of the select tag from other input tags in Angular?

I am having trouble displaying an error message for a select tag when it is in a touched state. The error handling seems to be working fine for other input tags, but not for the select tag. Below is the code snippet: <div class="form-g ...

A more concise approach to accessing a generic class method in Typescript

Let's analyze the code snippet below: export class BaseClass<T> { property = this.buildProperty(); buildProperty(){ return someBuilder<T>(); } } Through TypeScript, the type of property is automatically determined based on the ...

Installing and running Node.js within a tomcat server

After creating a web application using Angular, Node/Express, and MySQL, I faced an issue with deployment. My Angular app is running on a tomcat server connected to multiple PCs, but now I need to also deploy my backend (Node.js/Express.js) on the same s ...

Is it possible to integrate a personalized theme into react-dates?

Attempting to customize the styling of my react-dates DayPickerRangeController in Typescript using react-with-styles and Aphrodite. I have implemented the following code, mirroring the code found at https://github.com/airbnb/react-dates#interfaces: const ...

Unable to run unit tests on project using my custom React library

If any of you have encountered this issue or know how to solve it, please help me. I created an NPM package that can be found at https://www.npmjs.com/package/@applaudo/react-clapp-ui It installs and runs smoothly in other projects using create react app; ...

Leveraging File functionality in TypeScript

In the process of developing a web application with Angular 4 and Typescript, I encountered an issue while attempting to retrieve the date of a file for upload. Specifically, when trying to access the lastModified property of a File object, Typescript retu ...

Retrieve the data from the mat-checkbox

My goal is to retrieve a value from a mat-checkbox, but the issue is that we only get boolean expression instead of the string value. Here's an example snippet of what I'm looking for: <mat-checkbox formControlName="cb2" <strong&g ...

Examining the constructor condition

I am struggling to achieve a 100% test coverage by testing a condition within the constructor of a component. I have attempted various methods such as spying on the method during component creation, mocking the service, and other approaches but nothing h ...

Utilizing a background image property within a styled component - Exploring with Typescript and Next.js

How do I implement a `backgroung-image` passed as a `prop` in a styled component on a Typescript/Next.js project? I attempted it in styled.ts type Props = { img?: string } export const Wrapper = styled.div<Props>` width: 300px; height: 300px; ...

Encountering a TypeScript error when attempting to utilize indexOf on a Typed Array, leading to restriction

I have been working with an Interface, where I created an array of type Interface. I am currently facing some IDE error complaints when trying to use the .indexOf method on the Array. These errors seem confusing to me, and I'm hoping someone here migh ...

Unlocking the value of the "input" field within an EventListener function in Angular directly from the DOM

In my "characters" module, there is a form with a text field and a button. When the button is clicked, it triggers a function but I am struggling to retrieve the current input text and pass it to the async function. HTML: TS: Unfortunately, simply getti ...

Combining normal imports with top-level await: A guide

Is it possible to simultaneously use imports (import x from y) and top-level awaits with ts-node? I encountered an issue where changing my tsconfig.compilerOptions.module to es2017 or higher, as required by top-level awaits, resulted in the following error ...

The W3C Validator has found a discrepancy in the index.html file, specifically at the app-root location

While attempting to validate my HTML page, I encountered the following error: Error: Element app-root not allowed as child of element body in this context. (Suppressing further errors from this subtree.) From line 4347, column 7; to line 4347, column 16 ...

"Implementing material-ui in Angular 7: A Step-by-Step Guide

I am looking to integrate material-ui into my Angular 7 project. While I know that Angular Material is available, I prefer using ui-material over it. However, I am unsure about how to implement ui-material in an Angular environment. ...

Error thrown when attempting to pass additional argument through Thunk Middleware in Redux Toolkit using TypeScript

I have a question regarding customizing the Middleware provided by Redux Toolkit to include an extra argument. This additional argument is an instance of a Repository. During store configuration, I append this additional argument: export const store = con ...

When using Vue.js, you may encounter an error message stating that the `document.title` type of 'undefined' cannot be assigned to type 'string' in Typescript

I'm trying to use beforeEnter with Vue Router, but I encountered an error: TS2322: Type 'string | symbol | null | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string&apo ...

Leveraging components from external modules within sub-modules

So, I've created a module to export a component for use in different modules. However, I'm facing an issue with how to properly utilize this component within child modules of another parent module. While I have imported the first module into the ...