Jad*_*dda 1 angular-material angular angular10
在 Angular 10 项目中,我有一个表单,其中包含 2 个名为 Username 和 Password 的输入。我cdkFocusInitial在用户名字段上使用
属性,但它不关注页面加载。这是一个 StackBlitz 示例,显示了该问题https://stackblitz.com/edit/angular-4amzj4?file=src%2Fapp%2Ffocus-monitor-directives-example.html
<div class="example-focus-monitor">
<mat-form-field appearance="fill">
<mat-label>Username</mat-label>
<input cdkFocusInitial aria-label="Username" class="username"
matInput
placeholder="Enter Username" type="text">
</mat-form-field>
<br/>
<mat-form-field appearance="fill">
<mat-label>Password</mat-label>
<input aria-label=" Password" class="password" matInput placeholder="Enter Password"
type="text">
</mat-form-field>
</div>
[1]: https://stackblitz.com/edit/angular-4amzj4?file=src%2Fapp%2Ffocus-monitor-directives-example.html
Run Code Online (Sandbox Code Playgroud)
小智 10
这是因为 cdkFocusInitial 是在 FocusTrap 的上下文中使用的。你可以在这里读到它。
为了执行自动对焦,您可以创建一个指令,该指令将获取元素的引用并将其聚焦。
import { AfterContentInit, Directive, ElementRef, Input } from "@angular/core";
@Directive({
selector: "[autoFocus]"
})
export class AutofocusDirective implements AfterContentInit {
@Input() public appAutoFocus: boolean;
public constructor(private el: ElementRef) {}
public ngAfterContentInit() {
setTimeout(() => {
this.el.nativeElement.focus();
}, 100);
}
}
Run Code Online (Sandbox Code Playgroud)
使用这个指令就像
<input
autoFocus
aria-label="Username"
class="username"
matInput
placeholder="Enter Username"
type="text"
>
Run Code Online (Sandbox Code Playgroud)
如果您在一个页面上多次使用此选项,则最后一次使用的页面将成为焦点。干杯!
小智 6
添加第一个div:
cdkTrapFocus [cdkTrapFocusAutoCapture]="true"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3922 次 |
| 最近记录: |