I have an AngularDart component, how to get the text input field to auto-focus every time the component shows?
Asked Answered
M

1

6

I have a text input in a AngularDart component like the following:

<input type="email" id="inputFirstName" ng-model="cmp.inputFirstName">

How can I make the text input auto-focus every time the component shows?

I tried setting the html5 attribute autofocus, but that only works on the first time the component is displayed.

Missi answered 27/4, 2014 at 9:9 Comment(4)
Why does it show more often than once?Tapping
Because the component is on a view and this is a single page app, so the person comes back to the view for a second time and a third time and again and again. The component is just a simple form for entry of customer details.Missi
Have you tried using the .focus() function? Showing the component means there should be a enteredView() callback - so you could call .focus() on the input then?Brunel
enteredView() is from Polymer, the question is about Angular, but attach() is the equivalent in Angular.Tapping
U
5

You could try to use a custom Directive (new Decorator) for this:

import 'package:angular/angular.dart' as ng;
import 'dart:html';

@ng.Decorator(selector: '[autofocus]')
class AutoFocusDecorator implements ng.AttachAware{
  InputElement inputElement;

  AutoFocusDecorator(Element this.inputElement);

  @override
  void attach() {
    inputElement.focus();
  }
}

and use it like

<input type="email" id="inputFirstName" ng-model="cmp.inputFirstName" autofocus>
Upgrowth answered 27/4, 2014 at 9:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.