【问题标题】:How to get the active Element (the focused one) on Angular 6?如何在 Angular 6 上获得活动元素(重点元素)?
【发布时间】:2021-04-24 14:06:25
【问题描述】:

-- 不重复!由于其他问题已过时。不与问的问题重复!!!!

this.elm.nativeElement.ownerDocument.activeElement

还有

document.activeElement

奇怪地给了我整个身体。我怎样才能获得当前的焦点元素?

  • elm = ElementRef 的类型,绑定在我的组件的构造函数中。

  • 来自另一个问题:this.renderer.invokeElementMethod 也不可调用,因为 Renderer 现在已被弃用,而 Renderer2 显然不再具有该方法。

编辑:这个问题部分回答了这个问题:

document.activeelement returns body

在离开旧元素和进入新元素之间 活动元素确实是文档/正文本身。

【问题讨论】:

  • 尝试添加“自动对焦”属性。也试试 ngIf
  • 您没有关注任何有意义的元素这一事实并没有使这个问题独一无二,而是重复和特殊情况。
  • 你们中的一些人真的很奇怪.. 1- 不重复! 2- 我专注于有意义的元素 3- 请告诉我这个问题在哪里提出,答案适用于 Angular 6
  • document.activeElement 也给了我整个身体!

标签: angular angular6


【解决方案1】:

我必须在超时期间覆盖“document.activeElement”或“this.elm.nativeElement.ownerDocument.activeElement”,以便下一个角度生命周期检查活动元素。否则,在焦点更改后执行“X.activeElement”时,您会得到整个正文,因为在输入新元素时,活动元素确实是文档/正文本身。

setTimeout(function() {
  X = document.activeElement;
});

编辑 für ES6(也可以使用“this”):

setTimeout(() => {
  X = document.activeElement;
});

【讨论】:

  • 请记住,'this.*' 的范围在 setTimeout 中会发生变化,可以将其分配给另一个变量以在 setTimeout 中使用。这让我在遵循这个解决方案时有些小题大做。
  • 从 ES6 开始,最佳实践是使用arrow functions。那么this 将是您期望的范围(定义 setTimeout 的范围)。
【解决方案2】:

我之前遇到过类似的问题。我的问题是我在非表单元素上使用了“tabindex”,但我需要插入一个“onfocus”事件来调用组件操作。

两个选项对我有用:

1 指令

    @Directive({
      selector: '[componentFocus]'
    })
    export class ComponentFocus {
      @HostListener('focus')
      componentFocus() {
        console.log(`component has focus, element:`, this.el);
      }
    
      constructor(private el: ElementRef) {
      }
    }

然后调用类似字段集的东西:

    <fieldset tabindex="1" componentFocus>...</fieldset>

2 只需使用“聚焦”规范形式

    <fieldset tabindex="1" on-focus="onFocus($event.target)">...</fieldset>

【讨论】:

    猜你喜欢
    • 2012-09-13
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2021-08-12
    • 1970-01-01
    • 2016-12-16
    相关资源
    最近更新 更多