Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a string instead of expected number from Angular template and input native element's value

I have an event that fires on key up like this.

value: number;
onKeyUp(event: KeyboardEvent) {
  this.value = this.input.nativeElement.value;
  console.log("typo", typeof (this.value));
}

For some reason, the value stored is a string not a number. I've tried using syntax like this to no avail.

this.value = this.input.nativeElement.value as number;

Instead of that, I had to use the JS hack from the past, i.e. the unary plus operator like so.

this.value = +this.input.nativeElement.value;

Is there a more proper approach to make sure that my input provides a number? Or am I already doing it kinda right?

The markup provides no useful info, probably, but just in case, here it is.

<input #input
  value="{{value}}"
  (keyup)="onKeyUp($event)"
  (keydown.Tab)="onKeyUp($event)">
like image 531
Konrad Viltersten Avatar asked Apr 08 '19 17:04

Konrad Viltersten


Video Answer


1 Answers

It is written on the spec that value will always be stored as string. So even if you set the input type as number, it only update the user interface. But the value is still the same in string type.

I don't extract the data the same way with you. Not sure if you have any reason for doing so. I always use the ngModel directive.

Basically it is the two way binding, if you update the data model, it will update the UI and the other way around. So that you don't have to get the value manually through the ElementRef as you did on the question. It is done automatically for you.

app.component.html

<input type="number" [(ngModel)]="inputVal" (keyup)="onKeyUp($event)">

app.component.ts

onKeyUp(event: KeyboardEvent) {    
  console.log(this.inputVal);
}

Noted the type="number" on the HTML code. When you set it like that, the inputVal will be return as a number. I didn't really check the source code but probably Angular will parse it automatically somehow.

If you don't put it, the value will still be keep as a string.

I prepare the example for it. Please check https://stackblitz.com/edit/angular-ngmodel-number

You can just type into the input and see the value and the type.

like image 55
trungk18 Avatar answered Sep 30 '22 18:09

trungk18