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.

Phil
  • 46,436
  • 33
  • 110
  • 175
  • Why does it show more often than once? – Günter Zöchbauer Apr 27 '14 at 09:25
  • 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. – Phil Apr 27 '14 at 09:27
  • 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? – Robert Apr 27 '14 at 09:32
  • `enteredView()` is from Polymer, the question is about Angular, but `attach()` is the equivalent in Angular. – Günter Zöchbauer Apr 27 '14 at 09:48

1 Answers1

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>
Phil
  • 46,436
  • 33
  • 110
  • 175
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567