I try to create a custom DefaultValueAccessor. The Accessor should make a empty string to undefined.
How is it possible ?
Here is my code, that is not working.
import { Directive, forwardRef, Renderer2, ElementRef } from '@angular/core';
import { DefaultValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
export const VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => InputExtensionValueAccessor),
multi: true
};
@Directive({
selector: `
ion-input:not([type=checkbox]):not([type=radio]):not([type=password]):not([readonly]),
ion-textarea:not([readonly])[formControlName],
ion-textarea:not([readonly])[formControl],
ion-textarea:not([readonly])[ngModel]
`,
host: {
'(input)': '$any(this)._handleInput($event.target.value)',
'(blur)': 'onTouched()',
'(compositionstart)': '$any(this)._compositionStart()',
'(compositionend)': '$any(this)._compositionEnd($event.target.value)'
},
providers: [VALUE_ACCESSOR]
})
export class InputExtensionValueAccessor extends DefaultValueAccessor {
// HACK: Allows use of DefaultValueAccessor as base
// (https://github.com/angular/angular/issues/9146)
static decorators = undefined;
constructor(renderer: Renderer2, elementRef: ElementRef) {
// tslint:disable-next-line:no-null-keyword
super(renderer, elementRef, (null as any));
}
registerOnChange(fn: (_: any) => void): void {
super.registerOnChange(value => {
fn(value === '' ? undefined : value);
});
}
}