我是角色的新手,在我的应用程序中,我有一个mat对话框,其中有两种形式,即Login和SignUp。
一旦我第一次打开对话框,就会在用户名字段上设置自动对焦。问题是当我在按钮上导航到SignUp表单时单击该表单的FIrst Name字段不会自动聚焦,同样的方式从注册导航到登录用户名字段现在是没有自动聚焦。
我尝试了一些stackoverflow解决方案,但没有解决我的问题。
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>
任何人都可以帮我解决这个问题。
您可以使用MatInput进行设置自动对焦
这是一个例子,
在component.html
<mat-form-field>
<input matInput placeholder="First Name" #firstname="matInput">
</mat-form-field>
在component.ts
import { MatInput } from '@angular/material/input';
export class Component implements OnInit {
@ViewChild('firstname') nameInput: MatInput;
ngOnInit() {
this.nameInput.focus();
}
}
请在要聚焦的输入字段中使用“cdkFocusInitial”属性。
<mat-form-field>
<input matInput placeholder="username" #usernameInput cdkFocusInitial>
</mat-form-field>
差不多...... :-),如果你使用像MatSelect这样的材料组件 - 以上解决方案不起作用。您可以在下面找到适合我的解决方案。
<mat-form-field>
<mat-select #myElement ......>
..........
</mat-select>
<mat-form-field>
然后在组件......
@ViewChild('myElement') firstItem: MatSelect;
ngAfterViewInit() {
this.firstItem.focus();
this.cd.detectChanges();
}
请记住,在设置焦点后必须强制更改检测以避免Angular错误:“ExpressionChangedAfterItHasBeenCheckedError”(顺便说一下,您还必须在组件构造函数中包含“ChangeDetectorRef”)
希望这有帮助......
您是否尝试将autofocus
添加到名字的表单字段中?
<form class="SignUp" *ngIf="isSignUpHide">
<mat-form-field>
<input matInput placeholder="First Name" autofocus>
</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>
use可以使用native元素焦点。
没有测试过这段代码,但是这样的话:
<mat-form-field>
<input matInput placeholder="username" #usernameInput>
</mat-form-field>
在您的组件上:
@ViewChild('usernameInput') usrFld: ElementRef;
ngAfterViewInit() {
this.usrFld.nativeElement.focus();
}
p.s:您应该路由到注册组件而不是使用ngIf
进行导航。
这在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();
}
}