10

Normally, I would declare the input type this way (Which works great):

<input [(ngModel)]="input1" type="number" placeholder="Working"/>

How ever, I want the type to be dynamic, therefore I use property binding [type]="objectType". To simplify the question, I used [type]="'number'".

<input [(ngModel)]="input2" [type]="'number'" placeholder="Not Working"/>

Now the problem is that when ever I make a change to input2, it is converted to a string. That's not the case with input1 - it remains the number which is the expected behavior. How can I use property binding for type and prevent it from converting to string?

StackBlitz

Dino
  • 7,779
  • 12
  • 46
  • 85

3 Answers3

8

This is a known issue (see issue #13243).

A simple workaround for now is to use different inputs for each types :

@Input() public myInputType: string;
<input [(ngModel)]="value" type="number" *ngIf="myInputType === 'number'"/>
<input [(ngModel)]="value" type="text" *ngIf="myInputType === 'text'"/>
<!-- ... -->
Junior Dussouillez
  • 2,327
  • 3
  • 30
  • 39
  • This won't work either because the value is being stored in the model as either a number or string. – Brian Burton Nov 25 '19 at 08:29
  • It works if your value is declared as `value: number | string;` – Junior Dussouillez Nov 25 '19 at 08:35
  • Thanks, it's kinda odd the issue is still opened from 2016. This fixed the issue and will do it for now. – Dino Nov 25 '19 at 08:40
  • 2
    No sorry I wasn't clear, if the input field is a text field, the value gets saved to your model as a string. If it's a number type it gets saved as a number. So if the user enters a value and then the type is switched dynamically, it will remain either a number or string in your model and you've just introduced another bug into your code. https://stackblitz.com/edit/angular-g2mryc – Brian Burton Nov 25 '19 at 08:48
  • @BrianBurton Yes that's true. How ever the types I am getting are coming from an API and are locked afterwards. So there is no toggling with them. – Dino Nov 25 '19 at 08:58
1

This is a known bug that I've run up against as well, but the only solution right now is to manually cast the input value.

  logValues() {
    // Manually cast it as an integer (or float if need be)
    if (this.input2Type == 'number')
      this.input2 = parseInt(this.input2.replace(/[^\d]/g, ''));

    console.log('input1 =>', this.input1);
    console.log('input1 type => ', typeof(this.input1));
    console.log('input2 =>', this.input2);
    console.log('input2 type => ', typeof(this.input2));
  }
Brian Burton
  • 3,648
  • 16
  • 29
-2

If you want to dynamically change input type of a field you can try this. In your html

<input [type]="value">
<button (click)="onClick()">Change</button>

In your .ts file

value: string;
constructor(){
this.value = 'string';
}

onClick() {
  if (this.value == 'string') {
  this.value = 'number';
 }
else {
  this.value = 'string';
 }
}
Mridul
  • 1,320
  • 1
  • 5
  • 19