Jan Nielsen
Jan Nielsen

Reputation: 11799

Increment and decrement Angular Material slider via buttons

In addition to the slide features of the Angular Material (7.3) slider, my application has increment and decrement buttons which move the slider by one step. The increment and decrement buttons are external to the slider, duplicating the slider behavior with min, max, step, and keyboard interaction behavior.

Does anyone know of a way to avoid duplicating the logic by, perhaps, just feeding the slider "increment/decrement thyself" events?

Upvotes: 1

Views: 2963

Answers (2)

user10855567
user10855567

Reputation:

My suggestion would be to have a look at the code example they provide and click on the view source button ( which looks like this < >) for some more details about how to use the API.

It sounds like what you want is for the current value of the slider to be able to be changed from either the user directly interacting with the slider or by clicking on the buttons. The way that this can be accomplished is by using two-way data binding. This will allow for changes that occur when the button is pressed to be reflected in the current value of the slider as well as when the slider itself updates this value.

For the template:

<mat-slider
  [step]="step"
  [(ngModel)]="value">
<mat-slider>

In your component:

class ComponentClass {
  value = 0;
  step = 1;
  // other vals

  increaseSlider() {
    this.value += this.step;
  }

  decreaseSlider() {
    this.value -= this.step;
  }
}

These increaseSlider() and decreaseSlider() functions can be called from the button click events to trigger a change in the slider.

Upvotes: 1

Marshal
Marshal

Reputation: 11081

You could do the following to accomplish this.

Get a reference to your mat-slider in the component.

import {MatSlider} from '@angular/material';

@ViewChild(MatSlider) _matSlider: MatSlider;

Then create your increment and decrement methods.

Passing a positive number to the private _increment method will increment, passing a negative number will decrement... you then need to manually call the _emitInputEvent and the _emitChangeEvent methods to update the values.

public IncrementSlider(){
    this._matSlider['_increment'](1);
    this._matSlider['_emitInputEvent']();
    this._matSlider['_emitChangeEvent']();
  }

   public DecrementSlider(){
    this._matSlider['_increment'](-1);
    this._matSlider['_emitInputEvent']();
    this._matSlider['_emitChangeEvent']();
  }

Stackblitz

https://stackblitz.com/edit/angular-1bly2u?embed=1&file=app/slider-configurable-example.ts

Upvotes: 1

Related Questions