Having trouble getting focus() to work on textfield


#1

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>
        </StackLayout>
</StackLayout>

and in the component I am using this:

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

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


#2

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


#3

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(() => {
      this.secondTextFieldId.nativeElement.focus();
    }, 600);
  }

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

<TextField #secondTextFieldId ..>

#4

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.


#5

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

EDIT:

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