I'm trying to create an input that only allows for numbers to be typed in it, the problem is that this.modelChange.next(value)
doesn't appear to be firing unless I actually type a number.
Because if I type a 0
, then add a letter 0a
the model stays at 0
, and if I then add another digit 0a0
then the model updates and so does the input value since then the model has become 00
.
How can I make sure that an updates happens every time you enter something?
Component:
import {Component, Input, Output, EventEmitter} from 'angular2/core';
@Component({
selector: 'form-number-input',
templateUrl: './app/assets/scripts/modules/form-controls/form-number-input/form-number-input.component.html',
styleUrls: ['./app/assets/scripts/modules/form-controls/form-number-input/form-number-input.component.css'],
inputs: [
'model',
'alt',
'placeholder',
'name',
'label'
],
host: {
'(input)': 'isNum($event.target.value)'
}
})
export class FormNumberInputComponent {
@Input() model: number;
@Output() modelChange: EventEmitter = new EventEmitter();
isNum(value) {
value = value.replace(/[^0-9.-]/g, '');
this.modelChange.next(value);
}
}
Template:
<div>
<label attr.for="{{name}}">{{label}}</label>
<input [(ngModel)]="model" type="text" placeholder="{{placeholder}}" alt="{{alt}}" id="{{name}}" class="form-number-input">
</div>
Usage:
<form-number-input [(model)]="myNumber" label="Number" placeholder="Write a number" alt="Number input"></form-number-input>
EDIT: I found a solution to the problem, although it feels wrong:
isNum(value) {
this.modelChange.next(value);
value = value.replace(/[^0-9]/g, '');
this.modelChange.next(value);
}
By calling the modelChange
before AND after we manipulate the value both the input and the model gets updated, but WHY does this work?