0

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 :)

1 Answer 1

1

Try

angular.element('input').triggerHandler('focus');

or if it doesn't work

angular.element('input').triggerHandler('click');

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.