【问题标题】:cdkFocusInitial attribute not focusing the DOM elementcdkFocusInitial 属性不关注 DOM 元素
【发布时间】:2020-12-24 03:59:55
【问题描述】:

在 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

【问题讨论】:

    标签: angular angular-material angular10


    【解决方案1】:

    在第一个 div 中添加:

    cdkTrapFocus [cdkTrapFocusAutoCapture]="true" 
    

    https://stackblitz.com/edit/angular-4amzj4-nz2yh4?file=src%2Fapp%2Ffocus-monitor-directives-example.html

    【讨论】:

    • 需要在模块导入中添加A11yModule
    【解决方案2】:

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

    如果你在一个页面上多次使用它,它最后使用的那个将被聚焦。 干杯!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-12
      • 2018-07-02
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多