cdkFocusInitial 属性不聚焦 DOM 元素
cdkFocusInitial attribute not focusing the DOM element
在 Angular 10 项目中,我有一个表单,其中包含 2 个名为用户名和密码的输入。我在用
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
这是因为在FocusTrap的上下文中使用了cdkFocusInitial。你可以阅读它 here.
要执行自动对焦,您可以创建一个指令,该指令将获取元素的引用并将其聚焦。
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);
}
}
像
一样使用这个指令
<input autoFocus aria-label="Username" class="username"
matInput
placeholder="Enter Username" type="text">
如果您在一个页面上多次使用它,最后使用它的那个将被聚焦。
干杯!
先加入div:
cdkTrapFocus [cdkTrapFocusAutoCapture]="true"
在 Angular 10 项目中,我有一个表单,其中包含 2 个名为用户名和密码的输入。我在用
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
这是因为在FocusTrap的上下文中使用了cdkFocusInitial。你可以阅读它 here.
要执行自动对焦,您可以创建一个指令,该指令将获取元素的引用并将其聚焦。
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);
}
}
像
一样使用这个指令<input autoFocus aria-label="Username" class="username"
matInput
placeholder="Enter Username" type="text">
如果您在一个页面上多次使用它,最后使用它的那个将被聚焦。 干杯!
先加入div:
cdkTrapFocus [cdkTrapFocusAutoCapture]="true"