cdkFocusInitial属性未关注DOM元素

时间:2020-09-04 22:21:57

标签: angular angular-material angular10

在Angular 10项目中,我有一个带有2个输入的表单,分别名为Username和Password。我在用 用户名字段上的cdkFocusInitial属性,但是它并不关注页面加载。这是一个显示问题https://stackblitz.com/edit/angular-4amzj4?file=src%2Fapp%2Ffocus-monitor-directives-example.html

的StackBlitz示例
<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

2 个答案:

答案 0 :(得分:1)

这是因为在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">

如果您在页面上多次使用此功能,则将最后使用该页面。 干杯!

答案 1 :(得分:1)