0

I have input field in my template and I would like to catch each key press and update the value in the dom by removinf empty spaces - trim.

I can catch the event and the function I build is working correctly but the value in the input text field is not updated accordingly.

@HostListener('input', [ '$event.target.value' ])
   input( value ) {
   console.log('value! ' + value);
   value = value.replace(/\s/gi, '');
   console.log('value after trim ' + value);
   return true;

}

Any idea?

john Smith
  • 1,565
  • 7
  • 34
  • 54

3 Answers3

2

A simpler way to do it, with less code and the advantage of preventing space from being typed and the caret moving back on space like the accepted solution.

<input (keydown.space)="$event.preventDefault()">

Plunker here

Credit to answer here

BogdanC
  • 2,746
  • 2
  • 24
  • 22
1

When using Angular, try to actually USE Angular.

have [(ngModel)]="myInput" and (ngModelChange)="cleanup()" now create a function in the ts file:

cleanup() {
  this.myInput = this.myInput.replace(/ /g, '');
}
Carsten
  • 4,005
  • 21
  • 28
1

You can just use the keyup event and call a method to trim your value. Typescript provides you trim() function.

Your html will look like this:

<input (keyup)="keyUp($event)">

... and define the method in your typescript code:

keyUp(event){
    event.target.value = event.target.value.trim();
}

Link to Plunker Demo

FAISAL
  • 33,618
  • 10
  • 97
  • 105