简体   繁体   English

以编程方式聚焦并选择angular2材料设计输入

[英]Programmatically focus and select angular2 material design input

Using angular2 and angular2-material with following pattern: 使用带有以下图案的angular2和angular2-材料:

<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. 谢谢。

You can use the focus method from the md-input component as shown in the documentation 您可以使用md-input组件中的focus方法,如文档中所示

https://material.angular.io/components/input/api 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 来自评论的更新,感谢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. 永远记得取消订阅间隔。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM