Can't focus on Angular form text input after route change

不打扰是莪最后的温柔 提交于 2019-12-24 09:45:12

问题


I'm creating a form with Angular and Angular Messages. This form lies in a template that gets brought into the view with Angular Route. When I first load the form, everything functions properly. Then, when I load a different view and switch back to the form's view, I'm unable to focus on the text inputs. What's happening?

The HTML

<form name='submission' ng-submit='submit()'>

    <label class='text-input-group' for='name'>
        <div class='label'>Name</div>
        <input id='name' name='name' ng-model='submissionName' type='text' required>
        <div ng-messages='submission.name.$error' ng-if='submission.name.$touched'>
            <div ng-message='required'>* Please enter your name</div>
        </div>
    </label>

    <label class='text-input-group' for='email'>
        <div class='label'>Email</div>
        <input id='email' name='email' ng-model='submissionEmail' type='email' required>
        <div ng-messages='submission.email.$error' ng-if='submission.email.$touched'>
            <div ng-message='required'>* Please enter your email address</div>
            <div ng-message='email'>* Please enter a valid email address</div>
        </div>
    </label>

    <label class='text-input-group' for='message'>
        <div class='label'>Message</div>
        <textarea id='message' name='message' ng-model='submissionMessage' ng-maxlength='2000' maxlength='2000' required></textarea>
        <div ng-messages='submission.message.$error' ng-if='submission.message.$touched'>
            <div ng-message='required'>* No message?</div>
            <div ng-message='maxlength'>* Your message unfortunately can&#x27;t exceed 20,000 characters</div>
        </div>
    </label>

    <label class='checkbox-input-group' for='send-user-a-copy'>
        <div class='label'>Send me a copy</div>
        <input id='send-user-a-copy' name='sendUserACopy' ng-init='submissionSendUserACopy = false;' ng-model='submissionSendUserACopy' type='checkbox'>
    </label>

    <button type='submit'>Button</button>

</form>

The JavaScript

var contact = angular.module('app.contact', ['ngRoute']);

contact.config(['$routeProvider', function($routeProvider) {

    $routeProvider.when('/contact', {
        templateUrl: 'partials/contact.html',
        controller: 'ContactController'
    });

}]);

contact.controller('ContactController', ['$scope', function($scope) {

    $scope.reset = function() {
        $scope.submissionName = '';
        $scope.submissionEmail = '';
        $scope.submissionMessage = '';
        $scope.submissionSendUserACopy = '';
        $scope.submission.$setPristine();
    }

    $scope.$on('$routeChangeSuccess', function() {
        console.log($scope.submission);
        $scope.reset();
    });

    $scope.submit = function() {

        if($scope.submission.$valid) {
            console.log({
                'name' : $scope.submissionName,
                'email' : $scope.submissionEmail,
                'message' : $scope.submissionMessage,
                'sendUserACopy' : $scope.submissionSendUserACopy
            });
        }

    }

}]);

Any answers / suggestions would be greatly appreciated. Thank you!


回答1:


I wrote this to solve the issue with focus not applying on route changes in Angular.

import { Directive, ElementRef, AfterContentInit } from '@angular/core';

@Directive({
  selector: '[focusOnInit]'
})
export class FocusDirective implements AfterContentInit {

  constructor(public el: ElementRef) {}

  ngAfterContentInit() {
   this.el.nativeElement.focus();
  }
}

usage

<input type="text" focusOnInit>



回答2:


There is an attribute autofocus introduced in HTML5. I would suggest you adding that attribute in the first input element.

<input type="text" ng-model="firstName" autofocus />

But that has a limitation too!! Currently, browsers only focus on the input element directive on page load. So you will fall into the same problem that you are currently facing. So you can simply add an Angular directive with the same name i.e. autofocus which will programmatically focus the element as that directive is executed when the same view is loaded again.

myApp.directive('autofocus', [function() {
    return {
        restrict: 'A',
        link: function(scope, element) {
            element[0].focus();
        }
    };
}]);

(This is the format in Angular 1, please write it in Angular 2 if you are using Angular 2.)

Since even the same view has been loaded before, Angular will execute all the directives when the view is loaded again, this directive will focus the element after you switch back from another view.



来源:https://stackoverflow.com/questions/37617839/cant-focus-on-angular-form-text-input-after-route-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!