如何以角度2获取jquery范围滑块的值

时间:2016-04-26 09:02:03

标签: jquery angular rangeslider

我可以拖动滑块,但我不知道如何获取滑块的值..

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) {


        }
    });


}

}

2 个答案:

答案 0 :(得分:1)

您可以按照以下说明执行此操作:

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

请注意,使用箭头函数可以在组件属性slideValue中设置值。

修改

您可以将滑块包装到符合ngModel的组件中。以下是一个示例实现:

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; }
}

并以这种方式使用它:

@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;
  }
}

请参阅此plunkr:https://plnkr.co/edit/GJZUakH6O2wclHxpwOP2?p=preview

您可以查看本文以获取更多详细信息,请参阅&#34;与NgModel兼容的组件&#34;:

答案 1 :(得分:0)

为什么不只是简单地做

  updateValue() {
    this.sliderValue = 40;
    this.sliderElt.slider('value', this.sliderValue)
  }

将该功能放在滑块组件中,或者从外部调用它是否很重要?