Skip to content

Instantly share code, notes, and snippets.

@jcmartins
Created April 7, 2017 16:47
Show Gist options
  • Save jcmartins/d70537fb22311b6a08558b07c8882d5e to your computer and use it in GitHub Desktop.
Save jcmartins/d70537fb22311b6a08558b07c8882d5e to your computer and use it in GitHub Desktop.
import { FormControl } from '@angular/forms';
import { Component, EventEmitter, OnInit, Input, Output } from '@angular/core';
/*
Generated class for the NumberPicker component.
See https://angular.io/docs/ts/latest/api/core/index/ComponentMetadata-class.html
for more info on Angular 2 Components.
*/
@Component({
selector: 'number-picker',
templateUrl: 'number-picker.html'
})
export class NumberPickerComponent implements OnInit {
@Input() min: number;
@Input() max: number;
@Input() step: number;
@Input() precision: number;
@Input() inputDisabled: boolean;
@Output() onChange: EventEmitter<number> = new EventEmitter();
private numberPicker: FormControl;
constructor() { }
ngOnInit() {
if (this.inputDisabled == null) {
this.inputDisabled = false;
}
if (this.min == null) {
this.min = 0;
}
if (this.max == null) {
this.max = 100;
}
if (this.precision == null) {
this.precision = 1;
}
if (this.step == null) {
this.step = 1;
}
this.numberPicker = new FormControl({ value: this.min, disabled: this.inputDisabled });
this.numberPicker.registerOnChange(() => {
this.onChange.emit(this.numberPicker.value);
});
}
private increaseValue(): void {
var currentValue = this.numberPicker.value;
if (currentValue < this.max) {
currentValue = currentValue + this.step;
if (this.precision != null) {
currentValue = this.round(currentValue, this.precision);
}
this.numberPicker.setValue(currentValue);
}
}
private decreaseValue(): void {
var currentValue = this.numberPicker.value;
if (currentValue > this.min) {
currentValue = currentValue - this.step;
if (this.precision != null) {
currentValue = this.round(currentValue, this.precision);
}
this.numberPicker.setValue(currentValue);
}
}
private round(value: number, precision: number): number {
let multiplier: number = Math.pow(10, precision || 0);
return Math.round(value * multiplier) / multiplier;
}
public getValue(): number {
return this.numberPicker.value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment