1

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>
Chrillewoodz
  • 27,055
  • 21
  • 92
  • 175
  • I noticed you are using `slice` in the code, but in your question you say you are `splicing`. This is the issue I think, because slice returns a whole new array instead of changing it in-place like `splice` does. – Abdulrahman Alsoghayer May 14 '16 at 09:33
  • @Abdulrahman Ah sorry that was a typo. Thanks for pointing it out. I will try substring as splice doesn't work on strings. – Chrillewoodz May 14 '16 at 09:35
  • @Abdulrahman Same result with substring. – Chrillewoodz May 14 '16 at 09:36
  • Can you show your RegexService and where do you pass pattern input? – yurzui May 14 '16 at 09:46
  • @yurzui The RegexService isn't where the problem lies so I won't include it in the question as it's quite huge, and I don't pass a pattern as it defaults to integer if a pattern isn't given. – Chrillewoodz May 14 '16 at 09:48
  • Sorry I misunderstood the question, I thought it was an array. I see what are you doing now. I have created a simple [plunk](http://plnkr.co/edit/OHKvMrDRprz0GoTHaFgq?p=preview) – Abdulrahman Alsoghayer May 14 '16 at 10:05

1 Answers1

2

Try this:

this.onModelChange.emit(new String(value));

enter image description here

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/

yurzui
  • 205,937
  • 32
  • 433
  • 399