【问题标题】:create a directive to enable focus on input fields创建一个指令以启用对输入字段的关注
【发布时间】:2021-07-27 18:23:47
【问题描述】:

我尝试在我的应用程序的许多输入中激活焦点。我想我会创建一个自定义指令,而不是复制代码,但我做不到。 如果有人可以帮助我.. 这是我的错误代码: 指令:

import { AfterViewInit, Directive, ElementRef, ViewChild } from '@angular/core';

@Directive({
  selector: '[appFocus]'
})
export class FocusDirective implements AfterViewInit {
  @ViewChild('zone') zoneInput: ElementRef;
  constructor() { }

  ngAfterViewInit() {
     this.zoneInput.nativeElement.focus();
  }

}

在模板中:

        <div>
            <mat-form-field class="example-full-width" appearance="fill">
                <mat-label>Saisie code barre</mat-label>
                <input appFocus matInput formControlName="barcode" placeholder="EAN...">
            </mat-form-field>
        </div>

非常感谢

【问题讨论】:

  • 你很亲密。在构造函数中传递元素constructor(private host: ElementRef) {},然后您可以使用this.host.nativeElement.focus();访问它

标签: angular focus directive


【解决方案1】:

你已经接近了!

  constructor(private el: ElementRef) {}

  ngAfterViewInit(): void {
    this.el.nativeElement.focus();
  }

您需要实际传递元素,以便访问要关注的本机元素,而不是 zoneInput。您可能需要也可能不需要包装 setTimeout,但这应该可以满足您的需求。

【讨论】:

  • 非常感谢,它编译但我有以下错误: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked。 'mat-form-field-should-float' 的先前值:'false'。当前值:'true'..
  • 看起来不相关,我在您给我们的 sn-p 中的任何地方都看不到 mat-form-field-should-float。这看起来像是您可以搜索并找到它被使用的地方。它最有可能在 AfterView 或 AfterContent init 中使用,并且值在 doCheck 之前正在更改。可能想确保那些仅在 OnInit 中被引用。
  • 实际上,您可以将 ngAfterViewInit() 更改为 ngOnInit() 我假设,因为它有焦点,所以您有一个需要显示的浮动标签。
  • 我在不了解的情况下找到了问题的根源。有一个标签 mat-form-field 包含属性外观=“填充”。当我删除此属性时,错误消失了...我修改了我的帖子以向您显示表单的所有 html
  • 是的,很可能,触发该值为假(可能是焦点)的字段正在发生变化,当它最初检查时,它是假的,但在页面完成渲染后,它的是的,所以它会抛出该错误。无需将焦点放在 afterViewInit 中,只需将其放入 OnInit 或将其包装在 setTimeout 中即可。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 2018-06-02
  • 1970-01-01
  • 2012-09-14
  • 2018-03-31
  • 2015-03-04
相关资源
最近更新 更多