-6

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.

jabaa
  • 5,844
  • 3
  • 9
  • 30
  • you can not use `type=number` and use some kind of mask. Some time ago I made one for input in [this SO](https://stackoverflow.com/questions/58986023/need-angular-directive-digit-number-and-or-two-decimal-in-the-textbox/58991082#58991082) – Eliseo Jul 30 '21 at 08: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? – jabaa Jul 30 '21 at 08:53
  • can you try `control.valueAsNumber` ? https://twitter.com/stackblitz/status/1362048512943398914 – halilcakar Jul 30 '21 at 08:54
  • yes, is possible, simple pass the function the "htmlElement", for this you can use a template reference variable (see the answer) – Eliseo Jul 30 '21 at 08:56
  • @Eliseo I'm currently trying it. I think that's it – jabaa Jul 30 '21 at 08:56
  • @halilcakar That doesn't work with an Angular FormControl but it probably works with the fix in the answer – jabaa Jul 30 '21 at 08:57

1 Answers1

0

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);
  }
Eliseo
  • 50,109
  • 4
  • 29
  • 67
  • It works with `100.00` but it doesn't work with `100.`. When I enter `100.` it's still `100` without decimal separator. – jabaa Jul 30 '21 at 09:03