0

This is how I set the focus on a field in Angular 6. First, I declare the field in HTML:

<input type="text" name="myfield" [(ngModel)]="myfield" id="myfield" #focusMe /> 

Then in Javascript:

@ViewChild('focusMe') focusMe: ElementRef;

.....

this.focusMe.nativeElement.focus();

But I have a table and I need the focus on the first element; I don't know how to set #focusMe:

    <table>
        <tr *ngFor="let f of fields; let i = index">
            <td>
                {{f.name}}
            </td>
            <td>
                <input type="text" name="field{{i}}" [(ngModel)]="f.value" 
                    id="field{{i}}" />
            </td>
        </tr>
    </table> 

How to set the focus on the first input field?

ps0604
  • 1,227
  • 23
  • 133
  • 330
  • Have you tried the `autofocus` attribute? https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#autofocus – Alex K Jan 23 '19 at 20:13

1 Answers1

1

It's somewhat inefficient, but you can use the first property of @ViewChildren:

<table>
  <tr *ngFor="let f of fields; let i = index">
    <td>
      {{f.name}}
    </td>
    <td>
      <input #focusMe type="text" name="field{{i}}" [(ngModel)]="f.value" id="field{{i}}" />
    </td>
  </tr>
</table> 
@ViewChildren('focusMe') focusMe: QueryList<HTMLInputElement>;

.....

this.focusMe.first.nativeElement.focus();
night_owl
  • 856
  • 6
  • 12