Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set two way databinding on ng5 material slider value

I've got this application that uses angular5 together with material. While some examples and extra docs are lacking, development went fairly smooth. Until now, when I stumble upon this slider issue that I can't fix.

In my component I declare a myValue = 3 that is used as the default value of a <mat-slider>. I also plot this value in a <h2> right above it.

I can drag the slider and see the thumbLabel update. However, the {{myValue}} in the h2 does not update.

Do I need to manually 'get' the updated number? I can't seem to figure out how they are doing it in the docs.

I was thinking that maybe it had something to do with 'encapsulation' being loaded, but adding that made no difference.

How can I update {{myValue}} automatically whenever the slider value changes?

EDIT:

I'm using Angular 5 & material 5.2.4, not ng6. You can find an example of the code on: https://stackblitz.com/edit/angular-material2-issue-bbfwhn


EDIT2:

I found this post: How to get current value of angular material slider. It appears to work in my case, but I'm hoping there is a more elegant solution for this than writing a separate function in the component just to get the value back.

Also, this examples shows another easy way to get the value in the viewport: adding #matslider to the slider and getting the value in the html using {{matslider.value}}. I do however also need myValue in the component itself (to pass along to a provider).


EDIT3:

A dynamic way to solve this issue (when you have a lot of sliders) that expands upon How to get current value of Angular Material slider? is this:

component.ts:

setSlidervalue(event: any){
  this[event.source._elementRef.nativeElement.attributes.valvar.nodeValue] = event.value;
}

component.html:

<h2>slidervalue: {{testValue}}</h2>
<mat-slider min="1" max="5" step="0.5" [(value)]="testValue" (input)='setSlidervalue($event)' valVar="testValue"></mat-slider>

Using this solution, you can add more sliders like so:

<h2>onothervalue: {{someValue}}</h2>
    <mat-slider min="1" max="5" step="0.5" [(value)]="someValue" (input)='setSlidervalue($event)' valVar="someValue"></mat-slider>

The proposed solution works but is far from elegant. Leaving this question open in the hopes of finding a cleaner way to solve this.

like image 668
Wouter Vandenneucker Avatar asked Sep 02 '25 06:09

Wouter Vandenneucker


1 Answers

Use ngModel for two way binding.

app.component.html

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

app.component.ts

export class AppComponent {
  value = 1000;
}
like image 107
Houssem Romdhani Avatar answered Sep 05 '25 00:09

Houssem Romdhani