feat(numeric-input): create number input control value accessor

This commit is contained in:
Ken Sodemann
2017-12-11 11:01:34 -06:00
parent 4d36369a74
commit 903a12dc39
5 changed files with 105 additions and 4 deletions

View File

@ -0,0 +1,62 @@
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Directive({
/* tslint:disable-next-line:directive-selector */
selector: 'ion-input[type=number]',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: NumericValueAccessor,
multi: true
}
]
})
export class NumericValueAccessor implements ControlValueAccessor {
constructor(private element: ElementRef, private renderer: Renderer2) {
this.onChange = () => {};
this.onTouched = () => {};
}
onChange: (value: any) => void;
onTouched: () => void;
writeValue(value: any): void {
// The value needs to be normalized for IE9, otherwise it is set to 'null' when null
// Probably not an issue for us, but it doesn't really cost anything either
const normalizedValue = value == null ? '' : value;
this.renderer.setProperty(
this.element.nativeElement,
'value',
normalizedValue
);
}
@HostListener('input', ['$event.target.value'])
_handleInputEvent(value: any): void {
this.onChange(value);
}
@HostListener('ionBlur')
_handleBlurEvent(): void {
this.onTouched();
}
registerOnChange(fn: (_: number | null) => void): void {
this.onChange = value => {
fn(value == '' ? null : parseFloat(value));
};
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.renderer.setProperty(
this.element.nativeElement,
'disabled',
isDisabled
);
}
}

View File

@ -1,11 +1,9 @@
import { Directive, ElementRef, HostListener, Renderer2 } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
// NOTE: May need to look at this to see if we need anything else:
// https://github.com/angular/angular/blob/5.0.1/packages/forms/src/directives/default_value_accessor.ts#L33-L101
@Directive({
/* tslint:disable-next-line:directive-selector */
selector: 'ion-input,ion-textarea',
selector: 'ion-input:not([type=number]),ion-textarea',
providers: [
{
provide: NG_VALUE_ACCESSOR,
@ -44,4 +42,12 @@ export class TextValueAccessor implements ControlValueAccessor {
registerOnTouched(fn: () => void) {
this.onTouched = fn;
}
setDisabledState(isDisabled: boolean): void {
this.renderer.setProperty(
this.element.nativeElement,
'disabled',
isDisabled
);
}
}