angular 2 – 如何使用模板引用变量获取子组件的HTMLElement / ElementRef?

前端之家收集整理的这篇文章主要介绍了angular 2 – 如何使用模板引用变量获取子组件的HTMLElement / ElementRef?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试使用ViewChild获取子组件的元素,但无法找到实现此目的的方法.

我们在模板中说:

  1. ...
  2. <some-comp #someComp></some-comp>
  3. ...

并获得此参考:

  1. import { SomeComponent } from './some-comp/some-comp.component';
  2. ...
  3. @ViewChild('someComp') someComp: SomeComponent;
  4. ...
  5. ngOnInit() {
  6. // this.someComp.nativeElement? <-- how to get nativeElement?
  7. }

我试图这样做的原因是通过使用HTMLElement的scrollTo函数自动滚动到该子组件的位置,将视图集中到该子组件.(参见How to scroll element into view when it’s clicked)

我可以通过给那个子组件提供id并使用document.getElementById()来检索它,但我想知道是否有办法使用模板引用变量或任何角度方式来做到这一点.

提前致谢!

@ViewChild装饰器可以查询几个可以使用read参数指定的不同类型:
  1. @ViewChild(selector,{read: Type}) property;

这些类型可以是:

> ElementRef

@ViewChild(‘someComp’,{read:ElementRef})someComp;
> ViewContainerRef

@ViewChild(‘someComp’,{read:ViewContainerRef})someComp;

在你的情况下,它是你想要的ElementRef.

猜你在找的Angularjs相关文章