我正在尝试将 NoUiSlider(来自 Refreshless.com)包装在 Angular2 组件中(我不确定这本身是否是一个好主意;也愿意就此获得建议)。到目前为止,我已经能够创建一个滑块实例并通过一个函数管理它的事件。该函数虽然在我的组件外部,但无法将此类事件导出为我尝试创建的组件的输出属性。有什么建议吗?提前致谢。这是代码
///<reference path="../typings/nouislider/nouislider.d.ts" />
import {Component, ViewChild, AfterViewInit, Input, Output, EventEmitter} from 'angular2/core';
@Component({
selector: 'my-slider',
template: `
<div #sliderDomElement id="slider"></div>
`,
})
export class Slider implements AfterViewInit {
@ViewChild('sliderDomElement') sliderDomElement;
noUiSlider: any;
@Input() start: number[];
@Input() range: any;
@Input() pips: any;
@Output() end: EventEmitter<any> = new EventEmitter();
ngAfterViewInit() {
noUiSlider.create(this.sliderDomElement.nativeElement,
{start: this.start,
range: this.range,
pips: this.pips
});
this.noUiSlider = this.sliderDomElement.nativeElement.noUiSlider;
this.noUiSlider.on('end', logSlider);
}
}
function logSlider(inNoUiSlider: any) {
// the event is managed by this fuction, but I can not raise the event defined as Output by the component
console.log(inNoUiSlider);
}
经过更多挖掘(在 Typescript 中),我似乎找到了解决方案,即使用箭头函数表达式。这里是新代码
///<reference path="../typings/nouislider/nouislider.d.ts" />
import {Component, ViewChild, AfterViewInit, Input, Output, EventEmitter} from 'angular2/core';
@Component({
selector: 'my-slider',
template: `
<div #sliderDomElement id="slider"></div>
`,
})
export class Slider implements AfterViewInit {
@ViewChild('sliderDomElement') sliderDomElement;
noUiSlider: any;
@Input() start: number[];
@Input() range: any;
@Input() pips: any;
@Output() end: EventEmitter<any> = new EventEmitter();
public myLogSlider = (inValues: any[]) => {
console.log(inValues);
this.end.next(inValues);
}
ngAfterViewInit() {
noUiSlider.create(this.sliderDomElement.nativeElement,
{start: this.start,
range: this.range,
pips: this.pips
});
this.noUiSlider = this.sliderDomElement.nativeElement.noUiSlider;
this.noUiSlider.on('end', logSlider);
}
}