3

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?

Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • do you have plunker for the same? or show us your parent component which contains `form-number-input` tag. – micronyks Mar 27 '16 at 15:42
  • Why not use [input type=number](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input) ? – Eric Martinez Mar 27 '16 at 15:44
  • 1
    @EricMartinez Because it clears the input if I type 0a for example and doesn't allow floats. So figured it's best to use string and go from there which I also did in Angular 1 with nice results. – Chrillewoodz Mar 27 '16 at 15:45
  • @Chrillewoodz input type number [allow floats](http://stackoverflow.com/questions/19011861/is-there-a-float-input-type-in-html5). – Eric Martinez Mar 27 '16 at 15:49
  • @EricMartinez Didn't when I tried but maybe something else was wrong, either way it's not what I want. – Chrillewoodz Mar 27 '16 at 15:50
  • @micronyks I'm unable to get a plunkr working, so many angular 2 stuff that needs to be included it seems.. And I'm not great at plunkr. – Chrillewoodz Mar 27 '16 at 15:58

0 Answers0