Angular 2 Material input focus not working

Knack Kwenie picture Knack Kwenie · Apr 19, 2017 · Viewed 30.8k times · Source

The inputs are inside of a modal dialog. I have no idea why it is not working. I looked at the official docs and it listed focus as something you can pass to the element but it's not working?

Does anyone know why?

Angular Material - Input Docs

<form class="example-form">

  <md-input-container class="example-full-width" style="width: 300px; padding: 5px; border-radius: 10px;">
    <input mdInput type="email" name="to" placeholder="Email">
    <md-error></md-error>
  </md-input-container>

  <md-input-container focus focused>
    <input mdInput type="text" name="a" placeholder="zzzz" focus focused (focus)="">
  </md-input-container>

</form>

Answer

David Palita picture David Palita · May 24, 2017

Your attempts do not work because:

  • focused is a property driving the mat-focused class on mdInputContainer. You can use it to know whether your input is focused or not. You cannot use it to change the focus state.
  • focus is a method on mdInput that lets you programmatically focus the input. You can call the myInput.focus() with myInput being something like ViewChild('myInput') for instance.

But the simplest way to achieve what you want is to use the standard autofocus attribute :

<md-input-container>
    <input mdInput type="text" name="a" placeholder="zzzz" autofocus>
</md-input-container>