Take a look at this plunkr: https://plnkr.co/edit/xCvnJ9682lV0Z1sBcK68?p=preview (kudos to @yurzui from this question)
It makes sure that anything other than a valid format aren't allowed to be written in the input. There is a slight problem though, and that is if you write different letters quick you can enter things that aren't allowed. Or if just spamming the same letter real quick.
Here is the component:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'my-input',
template: '<input [(ngModel)]="model">',
inputs: [
'model'
],
host: {
'(input)': 'isNum($event.target.value)'
}
})
export class FormNumberInputComponent {
@Input() model: string;
@Output('modelChange') onModelChange: EventEmitter<any> = new EventEmitter();
isNum(value) {
const isNumeric = n => n === '-' || !isNaN(parseFloat(n)) && isFinite(n);
this.onModelChange.emit(isNumeric(value) ? value : new String(value.slice(0, -1)));
}
}
How can you make sure that Angular keeps up with the changes and don't allow things when writing too fast?