首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Angular 6中手动设置mat-form-field上的焦点

如何在Angular 6中手动设置mat-form-field上的焦点
EN

Stack Overflow用户
提问于 2018-09-03 12:11:46
回答 11查看 60.7K关注 0票数 27

我是angular的新手,在我的应用程序中,我有一个mat对话框,其中有两个表单,即Login和SignUp。

当我第一次打开对话框时,username field.problem上的自动焦点设置是当我导航到SignUp form on按钮时,单击该表单的first Name字段而不是自动聚焦,同样地,从注册到登录时,username字段现在不会自动聚焦。

我已经尝试了一些堆栈溢出的解决方案,但没有解决我的问题。

popupScreen.component.html

代码语言:javascript
复制
<form class="login" *ngIf="isLoginHide">
    <mat-form-field>
        <input matInput placeholder="username">
    </mat-form-field>
    <mat-form-field>
        <input matInput placeholder="password">
    </mat-form-field>

    <button mat-button color="primary">Login</button>
    <button mat-button (click)="hideLogin($event)" color="accent">SignUp</button>
</form>

<form class="SignUp" *ngIf="isSignUpHide">
    <mat-form-field>
        <input matInput placeholder="First Name">
    </mat-form-field>
    <mat-form-field>
        <input matInput placeholder="Last Name">
    </mat-form-field>
    <mat-form-field>
        <input matInput placeholder="username">
    </mat-form-field>
    <mat-form-field>
        <input matInput placeholder="password">
    </mat-form-field>

    <button mat-button (click)="hideSignUp($event)" color="primary">Login</button>
    <button mat-button color="accent">SignUp</button>
</form>

有人能帮我解决这个问题吗?

EN

回答 11

Stack Overflow用户

发布于 2019-01-17 15:05:04

请在您想要聚焦的输入字段中使用属性。

代码语言:javascript
复制
<mat-form-field>
    <input matInput placeholder="username" #usernameInput cdkFocusInitial>
</mat-form-field>
票数 29
EN

Stack Overflow用户

发布于 2019-02-21 03:39:52

差不多..。:-),如果您使用某些材质组件,如MatSelect -上述解决方案不起作用。下面你可以找到一个适合我的解决方案。

代码语言:javascript
复制
<mat-form-field>
    <mat-select #myElement ......>
       ..........
    </mat-select>
<mat-form-field>

然后在组件中...

代码语言:javascript
复制
@ViewChild('myElement') firstItem: MatSelect;

ngAfterViewInit() {
   this.firstItem.focus();
   this.cd.detectChanges();
}

请记住,您必须在设置焦点后强制进行更改检测,以避免角度错误:"ExpressionChangedAfterItHasBeenCheckedError“(顺便说一句,您还必须在组件构造函数中包含"ChangeDetectorRef”)

希望这能帮到你。

票数 25
EN

Stack Overflow用户

发布于 2019-08-09 15:35:35

这对我在Angular 8中是有效的:

代码语言:javascript
复制
<mat-form-field>
    <input matInput placeholder="First Name" #firstname>
</mat-form-field>

.ts

代码语言:javascript
复制
export class TestComponent implements OnInit {

    @ViewChild('firstname', {static: true}) firstname:any;

    ngOnInit() {
      this.firstname.nativeElement.focus();
    }

}
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52143052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档