How do I get the value of an input element using angular.element('#id')

All we need is an easy explanation of the problem, so here it is.

When I’m trying to get the value of input element using angular.element, its returning undefined.
Here is my code:

$scope.registerUser = function() {
    console.log(angular.element('#username').value); // undefined
    console.log(document.getElementById('username').value); // sampleName
};

How do I get the value using angular.element

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Explanation

You should use val method similar to jQuery’s $.fn.val:

console.log(angular.element('#username').val());

Alternatively you can use value property of the pure HTMLInputELement:

console.log(angular.element('#username')[0].value);

… because angular.element instance is an array-like collection of HTMLElements with every element accessible by its index.

Correct approach

But… You should never read input value like this in context of Angular app. Instead, use ngModel directive and bind input value to angular model directly:

$scope.registerUser = function() {    
    console.log($scope.username);
};

where in HTML you have

<input type="text" ng-model="username">

Method 2

This works for me

angular.element(document.getElementById('username')).val();

Method 3

In my angular-7 project, I solved by using these statement.

var field = document.getElementById('elementId'); 
var currentValue= field.getAttribute('value');
field.setAttribute('value','newValue');

Method 4

You can use below options for AngularJS 2+.

(<HTMLInputElement>document.getElementsByName("username")[0]).value
(<HTMLInputElement>document.getElementsById("username")[0]).value

Method 5

The same way as in jQuery, for which angular.element is a wrapper/sub:

angular.element('#username').val();

Method 6

In addition to the above ways,
these may also be used :

angular.element('[id="username"]').val();
angular.element('[id="username"]')[0].value;

Method 7

We can use "ViewChild" Decorator.

import { Component, Input, ViewChild, ElementRef} from '@angular/core';
@Component({
    selector: 'demo-input',
    templateUrl: 'demo.input.component.html'
})
export class DemoInputComponent {
    @ViewChild('inputEle') myDOMEle: ElementRef;

    getInputValue(){
       let val = this.myDOMEle.nativeElement.value;
    }
    setInputValue(){
       this.myDOMEle.nativeElement.value = "testing";
    }
}

In HTML(demo.input.component.html)

<input type="text" #inputEle/>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply