问题描述
我尝试使用带有angular2的Jquery-ui滑块。我想让变量slideValue显示滑块的值,但我无法弄清楚如何将我的模型或变量从角度绑定到滑块。这是我的滑块组件:
I try to use Jquery-ui slider with angular2. I would like to have the variable "slideValue" displaying the value of the slider but I can't figure out how to bind my model or a variable from angular to the slider. Here is my slider component:
import {Component, ElementRef, Inject, OnInit} from 'angular2/core';
declare var jQuery:any;
@Component({
selector: 'slider',
template:
`
<input type="text" [(ngModel)]="slideValue" id="amount" required placeholder="Enter a name here">
<div id="slider"></div>
<h2>slideValue = {{slideValue}}</h2>
`
})
export class Slider implements OnInit {
elementRef: ElementRef;
slideValue: number;
constructor(@Inject(ElementRef) elementRef: ElementRef) {
this.elementRef = elementRef;
}
ngOnInit() {
jQuery(this.elementRef.nativeElement).find("#slider").slider({
range: false,
orientation: "vertical",
min: 0,
max: 100,
value: 60,
slide: function( event, ui ) {
this.slideValue = ui.value; //doesn't seem to work
$( "#amount" ).val( ui.value );
}
});
}
}
此处的代码可用:
我希望能够使用Angular2的任何垂直滑块,所以如果存在另一个可行的解决方案,我很感兴趣(我检查了材料)但它似乎没有angular2准备好,只有水平滑块)。
I would like to be able to use any "vertical slider" with Angular2, so if another viable solution exists, I'm interested (i've check material but it doesn't seem to be "angular2" ready and only horizontal slider).
推荐答案
你需要在幻灯片中使用正确的上下文( this
)打回来。在这种情况下,箭头功能可以解决这个问题:
You need to use correct context (this
) inside of slide callback. Arrow function will do the trick in this case:
@Component({
selector: 'slider',
template: `
<input type="text" [(ngModel)]="slideValue" class="amount" required placeholder="Enter a name here">
<div class="slider"></div>
<h2>slideValue = {{slideValue}}</h2>
`
})
export class Slider implements OnInit {
elementRef: ElementRef;
slideValue: number;
constructor(@Inject(ElementRef) elementRef: ElementRef) {
this.elementRef = elementRef;
}
ngOnInit() {
var $amount = jQuery(this.elementRef.nativeElement).find(".amount");
jQuery(this.elementRef.nativeElement).find(".slider").slider({
range: false,
orientation: "vertical",
min: 0,
max: 100,
value: 60,
slide: (event, ui) => {
this.slideValue = ui.value;
$amount.val(ui.value);
}
});
}
}
这篇关于Angular2与Jquery-ui滑块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!