I am creating an angular application where a user needs to input a numerical value. I have an input box that looks like this:
<input class="input" type="number" id="index" min="1" max="20">
Next to the input box is a button that, when clicked, triggers a method that calls a function that looks like this:
getIndex(): number {
var input = +(<HTMLInputElement>document.getElementById('index')).value;
return input;
}
I input a number in the box and then click submit and the value for input is 0. I have separated it out so I can see the value before its converted to a number and it is an empty string. I can also see that it is getting the right element because the HTMLInputElement object has the correct class. I have also tried it by creating a global variable of the element and then getting the value from that after the button is clicked, like this:
// at the top of the file
inputEl = <HTMLInputElement>document.getElementById('index');
...
getIndex(): number {
return this.inputEl.value;;
}
I have found many, many questions on this topic but in every case, the value of the element was saved on page load and that is why it was empty when used. But in my case, I am only getting the value from the element after a value is entered and the submit button is clicked. Any help would be much appreciated.
4
Answers
Change the button type from submit to button. Type submit always refresh the page. You also don’t need to use any form also.
In your html file:
In your ts file:
instead using the document.getElementById, use
@ViewChild()
.e.g. in your template:
in your component:
Along with already given answers, you can also bind a value to input via ngModel:
Declare your variable in ts:
inputValue: number = null;
And Handle it on button click:
There are several ways to do what you need, so you can choose one that suits your need and project complexity.