Angular 2获取主机元素引用

buc*_*aci 43 typescript angular

如何在角度2中获取主机元素参考?在我的情况下,我想知道在我的组件中是否有焦点.可能吗?

最好的祝福!

Gün*_*uer 80

您将获得主机元素引用

class MyComponent {
  constructor(private elRef:ElementRef) {
    console.log(this.elRef.nativeElement);
  }
}
Run Code Online (Sandbox Code Playgroud)

您也可以订阅该focus活动

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

  • 嗯,这是正确的答案,但请注意 ElementRef 仅在 Angular 在浏览器线程中运行时才有效 - 您可以直接访问 DOM - 因此当您尝试在 webworker 中运行您的应用程序时会中断...... Renderer2 是在文档中提到 - 在这种情况下保存使用 - 但它被标记为实验性的,我还找不到关于如何使用它的好文档。也许这可以为某人省去我刚刚遇到的麻烦:) (2认同)
  • 使用`ElementRef`不是问题.问题是使用它的`nativeElement`属性.Angular团队强烈反对在预发布时使用`ElementRef.nativeElement`,但在发布后软化了他们的立场,因为很多人对WebWorker和Server-Side-Rendering不感兴趣.Renderer2的主要限制是它只允许设置元素的属性,但无法从中读取(否则它不适用于SSR和WW). (2认同)

Mos*_*van 5

使用ViewContainerRef表示一个容器,其中一个或多个视图可以附加到组件。

constructor(private readonly viewRef: ViewContainerRef) {

    console.log(this.viewRef.element.nativeElement);
}
Run Code Online (Sandbox Code Playgroud)