Reputation: 28328
I'm writing a component that should only allow certain number formats, it works great except for one thing, it slices the value every time but only updates the view every two times. So if I write it in this sequence:
A B C D
I end up with BD.
I can't understand what is happening here.
This is the component:
@Component({
selector: 'my-input',
templateUrl: 'my-input.html',
styleUrls: ['my-input.css'],
inputs: [
'model',
'pattern'
],
host: {
'(input)': 'isNum($event.target.value)'
},
providers: [
RegexService
]
})
export class FormNumberInputComponent {
@Input() model: number;
@Output('modelChange') onModelChange: EventEmitter<any> = new EventEmitter();
constructor(private _regexes: RegexService) {}
isNum(value) {
this.isInvalid = !this._regexes.test(this.pattern || 'integer', value);
if (!this.isInvalid) {
this.onModelChange.emit(value);
}
else {
value = value.slice(0, -1);
// This also doesn't work, gives the same result
value = value.substring(0, -1);
this.onModelChange.emit(value);
}
}
}
And the simple template:
<input [(ngModel)]="model">
Using it from parent component like this:
<my-input [(model)]="myModel1"></my-input>
Upvotes: 1
Views: 51
Reputation: 214027
Try this:
this.onModelChange.emit(new String(value));
Here is corresponding plunker https://plnkr.co/edit/2KqCGggSDOdXhjiJEw68?p=preview
I would write instead of component validation custom pipe for that: https://plnkr.co/edit/xCvnJ9682lV0Z1sBcK68?p=preview
Maybe it will be interesting also http://blog.jhades.org/how-does-angular-2-change-detection-really-work/
Upvotes: 2