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
Angular input type number allow numbers only HTML5 provides input type=number in web pages. This example tells to accept numbers only with allowing alphabets. This will be achieved with keypress event which is called when ever key is pressed in keyboard
numeric in the form is the basic level of validation in the Angular application. Input form type=text/number only allows numeric fields and other alphabets and special characters are not allowed. In Html numbers are entered via input form with input type=text in HTML4 or less, type=number in HTML5 language
To convert string to number in angular or typescript follow the below steps. Check if a string is number or not using Number () function. If the string is number then convert Number () returns the numeric value or NaN (Not a Number). We will take a sample typescript string and convert it to number. var stringToConvert = "759"; var numberValue = ...
For Angular versions,less than 8, viewChild is annotated with ElementRef type in component to read the input value. Finally, read the input value using ElementRef.nativeElement.value. Controller typescript component on reading input element value on button click.
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'"/>
<!-- ... -->
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With