I'm trying to implement a custom input that accepts only numeric values by reseting the rest to 0, using the following code for the input component:
import {Component, Input, Output, ElementRef, EventEmitter} from '@angular/core';
import {Observable} from 'rxjs/Rx';
@Component({
selector: 'debounce-input',
template: '<input type="text" [placeholder]="placeholder" [(ngModel)]="_v">'
})
export class DebounceInputComponent {
@Input() placeholder: string
@Input() delay: number = 300
_v: string
@Input()
get v(): string {
return this._v
}
set v(_value) {
this._v = _value
this.valueChange.emit(this.v)
}
@Output() valueChange: EventEmitter<any> = new EventEmitter<any>()
@Output() value: EventEmitter<any> = new EventEmitter<any>()
constructor(private elementRef: ElementRef) {
const eventStream = Observable.fromEvent(elementRef.nativeElement, 'keyup')
.map(() => this.v)
.debounceTime(this.delay)
.distinctUntilChanged()
eventStream.subscribe((obj) => this.value.emit({v: this.v}))
}
}
The component above is imported within AppComponent using the following code:
HTML part:
<div style="text-align:center"> <debounce-input [v]="mynumber" delay="1000" placeholder="Type something..." (value)="handle($event)"> </debounce-input> </div>TypeScript part:
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; mynumber = 0 handle(obj) { console.log(obj.v) if (isNaN(Number(obj.v))) { console.log('trying to reset invalid input to 0') this.mynumber = 0 } }}
The problem is whenever I type a non-numeric value, the AppComponent fails to reset the input to 0, although the "trying to reset invalid input to 0" message gets shown within the console.
What is the cause of this behavior?
console.log(obj.v)? did you try with obj.target.value?type="number"or saytype="text"