加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 08:33:37 所属栏目:安全 来源:网络整理
导读:我正在尝试使用ViewChild获取子组件的元素,但无法找到实现此目的的方法. 我们在模板中说: ...some-comp #someComp/some-comp... 并获得此参考: import { SomeComponent } from './some-comp/some-comp.component';...@ViewChild('someComp') someComp: Som
我正在尝试使用ViewChild获取子组件的元素,但无法找到实现此目的的方法.

我们在模板中说:

...
<some-comp #someComp></some-comp>
...

并获得此参考:

import { SomeComponent } from './some-comp/some-comp.component';
...
@ViewChild('someComp') someComp: SomeComponent;
...
ngOnInit() {
// this.someComp.nativeElement? <-- how to get nativeElement?
}

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

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

提前致谢!

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

这些类型可以是:

> ElementRef

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读