angularproperty-binding

Angular input [type]="'number'" always results in value being string


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


Solution

  • 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'"/>
    <!-- ... -->