我是angular的新手,在我的应用程序中,我有一个mat对话框,其中有两个表单,即Login和SignUp。
当我第一次打开对话框时,username field.problem上的自动焦点设置是当我导航到SignUp form on按钮时,单击该表单的first Name字段而不是自动聚焦,同样地,从注册到登录时,username字段现在不会自动聚焦。
我已经尝试了一些堆栈溢出的解决方案,但没有解决我的问题。
popupScreen.component.html
<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>有人能帮我解决这个问题吗?
发布于 2019-01-17 15:05:04
请在您想要聚焦的输入字段中使用属性。
<mat-form-field>
<input matInput placeholder="username" #usernameInput cdkFocusInitial>
</mat-form-field>发布于 2019-02-21 03:39:52
差不多..。:-),如果您使用某些材质组件,如MatSelect -上述解决方案不起作用。下面你可以找到一个适合我的解决方案。
<mat-form-field>
<mat-select #myElement ......>
..........
</mat-select>
<mat-form-field>然后在组件中...
@ViewChild('myElement') firstItem: MatSelect;
ngAfterViewInit() {
this.firstItem.focus();
this.cd.detectChanges();
}请记住,您必须在设置焦点后强制进行更改检测,以避免角度错误:"ExpressionChangedAfterItHasBeenCheckedError“(顺便说一句,您还必须在组件构造函数中包含"ChangeDetectorRef”)
希望这能帮到你。
发布于 2019-08-09 15:35:35
这对我在Angular 8中是有效的:
<mat-form-field>
<input matInput placeholder="First Name" #firstname>
</mat-form-field>.ts
export class TestComponent implements OnInit {
@ViewChild('firstname', {static: true}) firstname:any;
ngOnInit() {
this.firstname.nativeElement.focus();
}
}https://stackoverflow.com/questions/52143052
复制相似问题