【问题标题】:Programmatically focus and select angular2 material design input以编程方式聚焦并选择 angular2 材料设计输入
【发布时间】:2017-06-22 02:13:30
【问题描述】:

使用具有以下模式的 angular2 和 angular2-material:

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

如何以编程方式聚焦此(或任何其他)输入元素?如果可能的话,我还想在获得焦点后选择文本字段的内容。

谢谢。

【问题讨论】:

  • Gunter - 谢谢,但没有。我尝试过的类似代码在我的情况下不起作用。它可能与 angular2-material 有关。我正在寻找适用于该框架的解决方案。
  • 我不明白为什么会有所不同
  • - - 我也没有。

标签: angular focus angular-material


【解决方案1】:

您可以使用文档中显示的 md-input 组件中的 focus 方法

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>

从班级内部集中注意力:

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

来自 cmets 的更新,感谢 khoailang

您可以在短时间内使用超时设置焦点,以确保视图已初始化,并自动聚焦所需的输入

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();
        });
    }
}

永远记得取消订阅间隔。

【讨论】:

  • 你能提供一个plunker吗
  • 对不起,但我不知道如何在 plunker 中创建像 Angular 这样的项目。如果我的示例不起作用,请记住,当我编写它时,我使用的是 angular 4。
  • 谢谢,我发现了我的问题,我可以通过将 focus() 放在 setTimeout() 中来解决问题
  • @khoailang 最好使用订阅,别忘了取消订阅
猜你喜欢
  • 1970-01-01
  • 2019-04-10
  • 2020-03-27
  • 2016-05-09
  • 1970-01-01
  • 1970-01-01
  • 2019-07-08
  • 2018-06-01
  • 1970-01-01
相关资源
最近更新 更多