Ok, here is an example of how you can process user input in the place where it ought to be processed by design.
test-input.directive.ts
import { Directive, ElementRef, Renderer2, forwardRef, HostListener } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
export const TEST_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TestInputDirective),
multi: true
};
@Directive({
selector: 'input[appTestInput]',
providers: [TEST_VALUE_ACCESSOR]
})
export class TestInputDirective implements ControlValueAccessor {
onChange = (_: any) => { };
onTouched = () => { };
constructor(private _renderer: Renderer2, private _elementRef: ElementRef) { }
// this gets called when the value gets changed from the code outside
writeValue(value: any): void {
const normalizedValue = value == null ? '' : value;
this._renderer.setProperty(this._elementRef.nativeElement, 'value', normalizedValue);
}
registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
registerOnTouched(fn: () => void): void { this.onTouched = fn; }
setDisabledState(isDisabled: boolean): void {
this._renderer.setProperty(this._elementRef.nativeElement, 'disabled', isDisabled);
}
// just as an example - let's make this field accept only numbers
@HostListener('keydown', ['$event'])
_handleKeyDown($event: KeyboardEvent): void {
if (($event.keyCode < 48 || $event.keyCode > 57) && $event.keyCode !== 8) {
// not number or backspace, killing event
$event.preventDefault();
$event.stopPropagation();
}
}
@HostListener('input', ['$event'])
_handleInput($event: KeyboardEvent): void {
// this is what we should call to inform others that our value has changed
this.onChange((<any>$event.target).value);
}
}
Just add this directive declaration to your module:
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { TestInputDirective } from './test-input.directive';
@NgModule({
declarations: [
AppComponent,
TestInputDirective // <-- you'll need this
],
imports: [
BrowserModule,
FormsModule // <-- and this
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
And then you can use it in the template like this:
app.component.html
<input type="text" appTestInput [(ngModel)]="name">
<div>{{name}}</div>
That's a bit more code than with pipes, true, but this is proper way of handling user input, especially when it should be pre-processed in some way.