Having trouble getting focus() to work on textfield


Here is the code I am using:

<StackLayout class="form">
        <StackLayout class="input-field">
            <Label class="testClass2 label" text="Test TextField" ></Label>
            <TextField class="input input-border" id="firstTextFieldId" hint="This is a hint" text="" ></TextField>
            <TextField class="input input-border" id="secondTextFieldId" hint="This is a second hint" text="" ></TextField>

and in the component I am using this:

ngOnInit() {
        let focusTextField: TextField = <TextField> this.page.getViewById("secondTextFieldId");

The second textfield isn’t being focused on and the cursor is blinking in the first textfield. Any ideas?


After looking at it a little more, maybe focus() doesn’t actually focus the cursor to the field?


I think your focus() executes a bit too early.

You may not need the setTimeout below, but def use ngAfterViewInit instead of ngOnInit:

  @ViewChild("secondTextFieldId") secondTextFieldId: ElementRef;

  ngAfterViewInit(): void {
    setTimeout(() => {
    }, 600);

This code assumes you’ve added the id like this in your html:

<TextField #secondTextFieldId ..>


Thanks :slight_smile: Worked like a charm. I couldn’t get it to work without the setTimeOut. I tried with ngAfterViewChecked but that didn’t work either.


It is so annoying that it has to be wrapped with setTimeout


BTW it can also be set without Timeout with (layoutChange)="makeFocus()" ( 4.1)