When using ngx-slider in Angular, it unexpectedly fires off when scrolling on mobile devices

I am currently developing a survey application that utilizes ngx-sliders. However, I have encountered an issue on mobile devices where users unintentionally trigger the slider while scrolling through rows of slider questions, resulting in unintended changes to their answers.

I have attempted to disable the slider on the (touchmove) event, but it only works after the slider value has already been changed. Disabling it on (touchstart) does not yield the desired results either. Even after trying the touchEventsInterval slider option and using event.preventDefault(), I have had no success.

My latest attempt involves accessing the slider with ElementRef. One potential solution is to set the slider as readonly, detect a click at its position, mark that specific tick as active by changing its class, but I am facing difficulties in implementing this approach. I am uncertain if this method is effective or feasible.

At this point, I am running out of ideas and seeking advice on how to address this issue.

Here is a snippet of the HTML code:

<div class="slider-field hide-value-ticks mb-5">
  <div class="subtitle-black mb-4">{{answer.rowAnswerText ?? ''}} {{answer.columnAnswerText}}</div>
      <ngx-slider 
      *ngIf="options" 
      class="touch-slider" 
      [value]="selectedAnswer" 
      (valueChange)="sliderValueChange($event)" 
      [options]="options"
      (click)="onClick($event)
      #sliderNgx
      ></ngx-slider>
</div>

And here is the .ts file:


export class PathfinderStepSliderComponent implements OnInit {

  // Add the TypeScript code here

}

Answer №1

After much troubleshooting, I finally found a solution to my issue. By setting the readonly slider option to true and implementing a click listener, I was able to resolve the problem:

onSelectAnswer(e, slider) {
    // A bug was identified where clicking between ticks set the index to 2 (in the middle of the slider)
    const ignoreTargetClassName = 'ngx-slider-span ngx-slider-bar';
    
    const sliderElements = [...(slider.elementRef.nativeElement.getElementsByClassName(e.target.className) as any)];
    
    const index = sliderElements.findIndex(elem => elem === e.target);
    
    if (index !== -1 && (e.target.className !== ignoreTargetClassName)) {
      this.selectedAnswer = index;
    }
  }

Here is the updated HTML file:

<div class="slider-field hide-value-ticks mb-5">
  <div class="subtitle-black mb-4">{{answer.rowAnswerText ?? ''}} {{answer.columnAnswerText}}</div>
    <ngx-slider 
    id="slider"
    *ngIf="options" 
    class="touch-slider" 
    [value]="selectedAnswer" 
    (valueChange)="sliderValueChange($event)" 
    [options]="options"
    (click)="onSelectAnswer($event, ngxSlider)"
    #ngxSlider
    ></ngx-slider>
</div>

Answer №2

A different technique suggested in this Stack Overflow post involves utilizing the CSS property pointer-events.

You can set the .ngx-slider class to have pointer-events: none, while setting .ngx-slider-pointer to have pointer-events:all.

In my case, I had to nest these selectors within the ::ng-deep selector - you can refer to the custom-styling guide for ngx-slider for more information.

/* component.scss */
::ng-deep {
    .ngx-slider {
        /* In my scenario, I only want mobile and tablet users to be unable to interact with the slider. For desktop, I want them to be able to click to a specific value */
        @media (max-width: 768px) {
            pointer-events: none;
            .ngx-slider-pointer {
                pointer-events: all;
            }
        }
    }
}

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

Can you help me transition my angular website from English to Spanish using a radio button?

I want to develop an Angular website where users can select a language and click the next button to change all text on subsequent pages to that chosen language. For example, if a user selects Spanish, then all text on the following screens will be in Spani ...

Have there been any updates to ngFormControl in @angular/forms version 0.3.0?

I recently updated my Angular application from rc4 to rc5, along with upgrading angular forms from version 0.2.0 to 0.3.0. After the update, I started encountering an error that seems to be related to a change in ngFormControl within forms 0.3.0. zone.js: ...

Discovering Child Elements in Angular 2 with @ViewChild and CSS Selectors

I'm looking to update the style of the second paragraph using either the nth-child() selector or by a specific class: import { Component, ViewChild } from '@angular/core'; @Component({ selector: 'my-app', template: ` <d ...

Attempting to retrieve data either by code or with a WHERE condition proves unsuccessful as the data retrieval process yields no results

Seeking assistance with my Angular project that is utilizing a Node.js server and MSSQL express. I am having trouble retrieving data using a WHERE condition in my code. Any help in identifying the missing piece or error would be appreciated. Thank you. // ...

How to activate a textbox in Angular 6 when a checkbox is selected:

Looking for examples related to this topic, all I've come across are AngularJs examples. Is there a way to enable my textbox based on the status of a checkbox in the same row, without directly binding them through a boolean value or using JavaScript? ...

Using Angular ngx-bootstrap model without the need for ng-template

Looking to incorporate a bootstrap modal into my app, but I require the ability to customize the style of the modal myself. The example using ngx-bootstrap and ng-template doesn't allow for this level of customization. Are there any alternative soluti ...

Configuring NextJs routes with multiple parameters

Seeking guidance on structuring files in Nextjs for handling multiple URL parameters. Can anyone offer advice? The given URL structure is: /api/upload?file=${filename}&fileType=${fileType} This is the current file structure: app api upload ...

What is the most effective method to create a versatile function in Angular that can modify the values of numerous ngModel bindings simultaneously?

After working with Angular for a few weeks, I came across a problem that has me stumped. On a page, I have a list of about 100 button inputs, each representing a different value in my database. I've linked these inputs to models as shown in this snipp ...

Is there a way to replicate the tree structure of an array of objects into a different one while modifying the copied attributes?

Is there a way to replicate the tree structure of an array of objects to another one in TypeScript, with different or fewer attributes on the cloned version? Here's an example: [ { "name":"root_1", "extradata&qu ...

The File plugin in Ionic 3 is encountering difficulties in writing files on the device

I am developing an app using Ionic 3 and the file plugin. My goal is to write a JSON string to a JSON file located in my assets folder with the following hierarchy: assets -> mock -> msg-list.json , with "assets" as the main folder in the Ionic files. Wh ...

The ng2-intl encounters an issue when trying to resolve symbol values statically

I'm struggling with a common issue and can't seem to find a solution that works. My setup involves Angular 4.2.6 along with ng2-intl 2.0.0-rc.3. Despite trying the following code, I am still facing issues: export function intlFactory(http:Http ...

Picking up Angular component property values within a callback function from Google Charts

Trying to utilize the angular-google-charts library in Angular 13.2, I am working on creating a TreeMap with a customized tooltip feature. The GoogleChartComponent offers an options property called generateTooltip which requires a callback function. My goa ...

Angular 8: Issue with setErrors not reflecting on the template when marking a control as invalid

In my component, I am using the following code: this.frmGroup.controls['dorms'].setErrors({'incorrect': true}); For debugging purposes, I have added the following to my template: {{this.frmGroup.controls['dorms'].invali ...

Tips for identifying and handling a 400 bad request error in an HTTP response within an Angular 2 application

I attempted to handle the error 400 bad request in this manner: catch((error: any) => { if (error.status === 500) { return Observable.throw(new Error(error.status)); } else if (error.status === 400) { console.log( 'err ...

Angular2 marker with custom design for Google Maps

We have successfully implemented Angular2 Google Maps () and integrated Styled Google Maps using the following Plunkr: https://plnkr.co/edit/rv6udUOEedMxJejEpIW1 import { Directive } from '@angular/core'; import { GoogleMapsAPIWrapper } from &a ...

The issue with Angular2 Material select dropdown is that it remains open even after being toggled

Exploring the world of Node.js, I am delving into utilizing the dropdown feature from Angular Material. However, an issue arises once the dropdown is opened - it cannot be closed by simply clicking another region of the page. Additionally, the dropdown lis ...

Unable to reference the namespace 'ThemeDefinition' as a valid type within Vuetify

Looking to develop a unique theme for Vuetify v3.0.0-alpha.10 and I'm working with my vuetify.ts plugin file. import "@mdi/font/css/materialdesignicons.css"; import "vuetify/lib/styles/main.sass"; import { createVuetify, ThemeDefinition } from "v ...

Unlinked Typescript blob file name

Is there a way to set the file name for a blob in typescript? I have found a solution for IE, but it seems impossible for Chrome. I need something similar to this solution, but in typescript. downloadFile(data: any) { var blob = new Blob([data], {type ...

``I am facing an issue with Angular CLI where it is not compiling

Every time I attempt to install a new package, npm mysteriously removes all packages associated with the angular cli. Upon reinstalling angular cli, I encounter the following error message: C:\SomeApp\Main\WebUI>ng serve The "@angular/c ...

Creating tests in JestJs for React components that utilize Context Provider and Hooks

As a newcomer to front-end development, I am currently working on authentication with Okta-React. To pass logged-in user information across multiple components, I'm utilizing React context with hooks. While this approach works well, I encountered an i ...