skip to Main Content

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


  1. Change the button type from submit to button. Type submit always refresh the page. You also don’t need to use any form also.

    Login or Signup to reply.
  2. In your html file:

    <input class="input" type="number" min="1" max="20" #input>
    <button (click)="getIndex(input.value)">Click</button>
    

    In your ts file:

    getIndex(value: number) {
       console.log(value);
    }
    
    Login or Signup to reply.
  3. instead using the document.getElementById, use @ViewChild().
    e.g. in your template:

    <input #input class="input" type="number" id="index" min="1" max="20">
    

    in your component:

    @ViewChild('input') inputElement: ElementRef<HTMLInputElement>;
    ...
    getIndex(): number {
      return this.inputElement.nativeElement.value;;
    }
    
    Login or Signup to reply.
  4. Along with already given answers, you can also bind a value to input via ngModel:

    <input type="number" min="1" max="20" [(ngModel)]="inputValue" />
    <button (click)="handleInputValue()">Click</button>
    

    Declare your variable in ts: inputValue: number = null;

    And Handle it on button click:

    handleInputValue() {
        console.log(this.inputValue)
    }
    

    There are several ways to do what you need, so you can choose one that suits your need and project complexity.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search