gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:06:37 25 4
gpt4 key购买 nike

我正在尝试使用 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 函数自动滚动到该子组件的位置来将 View 聚焦到该子组件。(参见 How to scroll element into view when it's clicked )

我可以通过为该子组件提供 id 并使用 document.getElementById() 进行检索来实现它,但我想知道是否有一种方法可以使用模板引用变量或任何 Angular 方式来做到这一点。

提前致谢!

最佳答案

@ViewChild 装饰器可以查询几种不同的类型,这些类型可以使用 read 参数指定:

@ViewChild(selector, {read: Type}) property;

这些类型可以是:

  • 元素引用

    @ViewChild('someComp', {read: ElementRef}) someComp;

  • ViewContainerRef

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

在您的情况下,您需要的是 ElementRef

关于angular 2 - 如何使用模板引用变量获取子组件的 HTMLElement/ElementRef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44047713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com