I've tried filling the value on init with a "-" sign but only got the Error-Message:
The specified value "-" cannot be parsed, or is out of range.
Another attempt was to just accept every value as negative if it doesn't start with a " " sign but when reading the value property the sign wasn't included.
Does anyone know an easy way to handle an input type="number" as a negative and only make it positive when explicitly stated?
Preferably in a user-friendly way. I don't want a check-box to handle that.
Specifics:
i have an input Field in html
<input type="number" #testAmount>
I want to handle the value as negative when not explicitly stated otherwise.
so my first attempt was this in TS:
@ViewChild('testAmount') testAmount: ElementRef<HTMLInputElement> | undefined = undefined;
ngOnInit() {
if(!!this.testAmount){
console.log('set amount value');
console.log(this.testAmount.nativeElement.value);
this.testAmount.nativeElement.value = '-'
}
}
that's when i got the error message above:
The specified value "-" cannot be parsed, or is out of range.
Attempt 2:
In my second attempt figured to just accept any value and treat it as negative and only once the user puts a " " before the value it would be a positive.
but that didn't work out, because when i read the value like this:
console.log(this.testAmount.nativeElement.value)
i was given the value without the sign, presumably because it was interpreted as a number and thus the sign was automatically removed.
To Be clear All i want is that the user doesn't have to add the minus sign every time he adds a value, because negative values will be the norm.
But a positive value shall still be possible it is just rather rare.
Solution?
Best solution i've found so far is to give my input a KeyDown event and handle the very first key-input, it's not perfect but i think it'll get the job done most of the time:
inputHasBeenMade = false
onKeyDown(event: KeyboardEvent) {
if(!this.inputHasBeenMade && !!this.amount){
if(event.key !== " "){
event.preventDefault()
this.amount.nativeElement.value = '-' event.key
}
this.inputHasBeenMade = true
}
}
i don't think it's a good solution so i won't write it down as an answer (for now) in the hopes that someone will come up with a better solution.
CodePudding user response:
type number can't have a "-" string.
you can specify -78 or some other number without the ""
CodePudding user response:
Change
let myValue = '-';
this.testAmount.nativeElement.value = myValue
To
let myValue = -5;
this.testAmount.nativeElement.value = myValue;
You are creating a minus
symbol when you wrap it with a single '
or a "
double quote, and this makes it a string. Remove the quotes and it will be an integer.
You can also look at casting a string to an int if that's required, but not good practice.