如何在Angular 6上获得活动元素(集中的元素)?

时间:2018-09-27 07:01:07

标签: angular angular6

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

this.elm.nativeElement.ownerDocument.activeElement

document.activeElement

给我足够奇怪的整个身体。我如何才能获得当前关注的元素?

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

  • 来自另一个问题:this.renderer.invokeElementMethod也不可调用,因为现在不推荐使用Renderer,并且Renderer2显然不再具有该方法。

编辑:此问题部分回答了此问题:

document.activeelement returns body

  

在离开旧元素并输入新元素之间,   活动元素确实是文档/主体本身。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:1)

我之前有一个类似的问题。我的问题是我在非表单元素上使用“ 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>
相关问题