I've been working on a project where we wanted to load a screen and set it to the default state. It isn't that hard to do with Angular. This will show you how.

Set up a Basic Project

I started by creating a default Angular project with ng new. This will run you through the wizard and create a default component. For the purposes of this sample we're going to just modify the default component, app.component.

You can run the project using ng serve.

Create the Inputs

In a real world app there are plenty of ways to create your inputs. For the sake of this, we're going to create a bunch of inputs in a loop. Open up the app.component.html file:

view plain print about
1<div *ngFor="let x of [0, 1, 2, 3, 4]">
2 <b>Input {{x}}</b>: <input #input> <button (click)="onClick(x)">Set Focus</button><br/>

The code uses ngFor to loop over an array. We give each input a label and a button. The button calls a method named onClick() which will give focus to the correct input.

Set focus on a click

Open up the app.component.ts file. First step is to get access to the ViewChildren:

view plain print about
1@ViewChildren('input') inputs: QueryList<ElementRef>;

The input string in the ViewChildren() metadata refers to the #input text in the HTML input. Since we are referring to an array of inputs we use ViewChildren and QueryList instead of ViewChild and ElementRef. The QueryList is sort of like an array of all the HTML elements.

Now, create the onClick() method:

view plain print about
1onClick(index) {
2 this.inputs.toArray()[index].nativeElement.focus();
3 }

The argument into the method is an index, referring to the item we want to put focus on. The method converts the QueryList inputs into an array using the toArray() method. Then it references the specific element using the index, accesses the nativeElement. The nativeElement references the actual HTML DOM element and is only supposed to be used or accessed sparingly. Finally, call the focus() method on the nativeElement.

We should be good to go.

Run the Code

Run the code in a browser. You should see something like this:

Click the buttons on the right and you should see focus being set to the proper input:

Now you know how to set focus on an input within Angular.

Play with the code here

Next week I'm going to show you how to test the onClick() method