htmlangularangular-materialmat-slider

Angular material range slider : changing values ​programmatically runs into a consistency check


I need to programmatically modify the values ​​of the range material slider. But the slider component seems to check the start-end consistency before the two values ​​are even updated.

So if the current range is 10-30 on a 0-100 slider and I want to programmatically change it to 80-100, the slider ends up displaying the range 30-100. I think it starts by updating the start value (80), but since the end value is still 30, it limits it to 30.

import { Component } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { MatSliderModule } from '@angular/material/slider';
import { FormsModule } from '@angular/forms';

@Component({
  selector: 'app-root',
  template: `
    <div style="margin: 20px;">
      <mat-slider min="0" max="100" step="10" style="width: 100%" showTickMarks>
        <input [(ngModel)]="sliderStart" matSliderStartThumb>
        <input [(ngModel)]="sliderEnd" matSliderEndThumb>
      </mat-slider>
    </div>
    <div>
      sliderStart : {{ sliderStart }} <br>
      sliderEnd : {{ sliderEnd }} <br>
    </div>
    <div style="margin-top: 10px; display: flex; gap: 10px;">
      <button (click)="reset()">reset</button>
      <button (click)="changeTo2050()">change to 20-50</button>
      <button (click)="changeTo80100()">change to 80-100</button>
    </div>
  `,
  imports: [FormsModule, MatSliderModule],
})
export class App {
  sliderStart = 10;
  sliderEnd = 30;

  reset() {
    this.sliderStart = 10;
    this.sliderEnd = 30;
  }
  changeTo2050() {
    this.sliderStart = 20;
    this.sliderEnd = 50;
  }
  changeTo80100() {
    this.sliderEnd = 100;
    this.sliderStart = 80;
  }
}

bootstrapApplication(App);

Stackblitz Demo

I've tried several techniques to overcome this, without success...

Do you have a solution ?

Thank you very much!


Solution

  • Here's a solution to my problem. With a timer that acts on either of the interval limits, it works.

    In the example below, I set the timer to 0.3 seconds for better understanding.

    https://stackblitz.com/edit/stackblitz-starters-p4b3rgdy?file=src%2Fmain.ts