-12

Is it possible to get the raw string value of an input with type number?

Example code

import { Component } from '@angular/core'; import { FormBuilder, FormControl } from '@angular/forms'; @Component({ selector: 'my-app', template: ` <input type="number" [formControl]="control" (ngModelChange)="getStringValue(control)" /> ` }) export class AppComponent { control = this.fb.control(''); constructor(private fb: FormBuilder) {} getStringValue(control: FormControl): void { console.log(control.value); } } 

Stackblitz

Assuming I can't change the template (it's a requirement by the client) and I want to get the number of decimals or check if this number contains a decimal separator, is this possible?

When I enter 100.00 or 100. into the input field the property control.value contains 100. I can't find any method like getRawValue to access the underlying string.

I know I can suggest to change the type of the input element to text but first I have to find out if there are other ways to solve this.

6
  • you can not use type=number and use some kind of mask. Some time ago I made one for input in this SO Commented Jul 30, 2021 at 8:52
  • @Eliseo "I know I can suggest to change the type of the input element to text but first I have to find out if there are other ways to solve this." I can solve it with type text. That's pretty easy. But is it also possible with type number? Commented Jul 30, 2021 at 8:53
  • can you try control.valueAsNumber ? twitter.com/stackblitz/status/1362048512943398914 Commented Jul 30, 2021 at 8:54
  • yes, is possible, simple pass the function the "htmlElement", for this you can use a template reference variable (see the answer) Commented Jul 30, 2021 at 8:56
  • @Eliseo I'm currently trying it. I think that's it Commented Jul 30, 2021 at 8:56

1 Answer 1

1

you can get the "HTMLElement", I like use a template reference variable,

<input #inputControl type="number" [formControl]="control" (ngModelChange)="getStringValue(inputControl)" /> getStringValue(control: any): void { console.log(control.value); } 
Sign up to request clarification or add additional context in comments.

1 Comment

It works with 100.00 but it doesn't work with 100.. When I enter 100. it's still 100 without decimal separator.