Reputation: 1075
I'm trying to get the current input focus dinamically with angular and typescript. I'm using the angular.element([selector]).focus(handler) function but it does not trigger when i click on an input.
This is my code:
class TemplateController {
lastFocused: HTMLInputElement;
static $inject = ['$scope'];
constructor(private $scope: ng.IScope) {
angular.element("input[type='text']").focus((): void => {
this.lastFocused = document.activeElement as HTMLInputElement;
console.log("FOCUSED");
});
}
}
angular
.module("app")
.controller("[...]templateController", TemplateController);
}
And this is my html (input snippet):
...
<input class="form-control" type="text" id="title" name="title" size="30" ng-maxlength="1000" required />
...
What I'm doing wrong?
Thanks in advance :)
EDIT: Solved
I was able to solve this problem by using ng-focus attribute on the input element:
<input class="form-control" type="text" id="title" name="title" size="30" ng-maxlength="1000" required ng-focus="templateCtrl.setFocusedElement()" />
and inside the controller:
setFocusedElement(): void {
this.$scope.lastFocused = document.activeElement;
}
This works fine for me :)
Upvotes: 0
Views: 3109
Reputation: 49817
Try
angular.element('input').triggerHandler('focus');
or if it doesn't work
angular.element('input').triggerHandler('click');
Upvotes: 1