How to get host element reference?

后端 未结 1 1384
感情败类
感情败类 2021-02-04 23:30

How can I get the host element reference in Angular 2?

In my case, I want to know if my component has a focus or not.

1条回答
  •  北恋
    北恋 (楼主)
    2021-02-04 23:46

    You get the host element reference using

    class MyComponent {
      constructor(private elRef:ElementRef) {
        console.log(this.elRef.nativeElement);
      }
    }
    

    You can also subscribe to the focus event

    class MyComponent {
      @HostBinding() tabindex = 0;
      @HostListener('focus', ['$event'])
      onFocus(event) {
        console.log(event);
      }
    }
    

    0 讨论(0)
提交回复
热议问题