Search code examples
jqueryangularrangeslider

How to get the value of the jquery range slider in angular 2


I am able to drag the slider but i don't how to get the values of the slider ..

ngOnInit() {             
    jQuery(this.elementRef.nativeElement).find("#slider").slider({
        range:true,
        orientation: "horizontal",
        min: 0,
        max: 100,
        step:1,
        value: [80, 100],

        slide: function (event, ui) {


        }
    });


}

}


Solution

  • You can do this as described below:

    ngOnInit() {             
      jQuery(this.elementRef.nativeElement).find("#slider").slider({
        (...)
        slide: ( event, ui ) => {
          this.slideValue = ui.value;
        }
      }
    }
    

    Notice the use of an arrow function to be able to set the value in the component property slideValue.

    Edit

    You can wrap the slider into an ngModel-compliant component. Here is a sample implementation:

    const SLIDER_VALUE_ACCESSOR = new Provider(
      NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => SliderComponent), multi: true});
    
    @Component({
      selector: 'slider',
      template: `
        <div class="slider"></div>
      `,
      providers: [ SLIDER_VALUE_ACCESSOR ]
    })
    export class SliderComponent implements ControlValueAccessor {
      onChange = (_) => {};
      onTouched = () => {};
    
      constructor(private elementRef:ElementRef) {
    
      }
    
      ngAfterViewInit() {
        this.sliderElt = $(this.elementRef.nativeElement).find('.slider');
        this.sliderElt.slider({
          range:true,
          orientation: "horizontal",
          min: 0,
          max: 100,
          step:1,
          range: false,
          value: this.value,
          slide: (event, ui) => {
            this.onChange(ui.value);
          }
        });
        this.initialized = true;
      }
    
      writeValue(value:any):void {
        if (value!=null) {
          if (this.initialized) {
            this.sliderElt.slider('value', value);
          } else {
            this.value = value;
          }
        }
      }
    
      registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
      registerOnTouched(fn: () => void): void { this.onTouched = fn; }
    }
    

    And use it this way:

    @Component({
      selector: 'app'
      template: `
        <div>
          <slider [(ngModel)]="sliderValue"></slider>
          sliderValue: {{sliderValue}}<br/>
          <div (click)="updateValue()">update value</div>
        </div>
      `,
      directives: [ SliderComponent ]
    })
    export class App {
      sliderValue = 0;
    
      updateValue() {
        this.sliderValue = 40;
      }
    }
    

    See this plunkr: https://plnkr.co/edit/GJZUakH6O2wclHxpwOP2?p=preview

    You could have a look at this article for more details in section "NgModel-compatible component":