Reputation: 821
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
Upvotes: 21
Views: 109095
Reputation: 777
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/>
Upvotes: 0
Reputation: 111
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');
Upvotes: 2
Reputation: 107
You can use below options for AngularJS 2+.
(<HTMLInputElement>document.getElementsByName("username")[0]).value
(<HTMLInputElement>document.getElementsById("username")[0]).value
Upvotes: 1
Reputation: 827
This works for me
angular.element(document.getElementById('username')).val();
Upvotes: 2
Reputation: 193311
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.
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">
Upvotes: 21
Reputation: 5
In addition to the above ways, these may also be used :
angular.element('[id="username"]').val();
angular.element('[id="username"]')[0].value;
Upvotes: 0
Reputation: 1546
The same way as in jQuery, for which angular.element
is a wrapper/sub:
angular.element('#username').val();
Upvotes: 0