1

Using angular2 and angular2-material with following pattern:

<form #userForm="ngForm" style="background-color: rgba(209,216,239,0.29)" layout-padding="20px">
        <div layout="row" layout-margin>
          <md-input-container flex>
            <input md-input
                   #eAccountName
                   #cAccountName="ngModel"
                   type="text"
                   placeholder="Account Name"
                   [(ngModel)]="accountName"
                   name="accountname"
                   maxlength="50"
                   [disabled]="!isEditable"
                   required>
          </md-input-container>
        </div>
</form>

How do I programmatically focus this (or any other) input element? If possible, I'd also like to select the contents of the text field once its focused.

Thanks.

CCPony
  • 988
  • 1
  • 7
  • 20

1 Answers1

0

You can use the focus method from the md-input component as shown in the documentation

https://material.angular.io/components/input/api

<span (click)="myinput.focus()">Focus it!</span>
<md-input-container class="example-full-width">
    <input mdInput #myinput>
</md-input-container>

To focus from inside a class:

export class AppComponent {
    @ViewChild('myinput') articleInput;
    someMethod() {
        this.articleInput.nativeElement.focus();
    }
}

Update from comments, thanks to khoailang

You can use a timeout to set focus after a short period of time, to be sure the view is initialized, and autofocus the desired input

export class MyDemoComponent implements AfterViewInit {
    interval: Subscription;
    @ViewChild('viewInputName') input;

    ngAfterViewInit() {
        this.interval = Observable.interval(750).subscribe(x => {
            this.input.nativeElement.focus();
            this.interval.unsubscribe();
        });
    }
}

Always remember to unsubscribe from the interval.

alvaropgl
  • 830
  • 8
  • 19