英文:
How to take DOM element from template inside the component's class?
问题
我的用例是在内部获取边界客户端矩形并将其用于定位一个与视口相关的容器(上下文菜单)。
Angular允许您使用@ViewChild('hashedId') someVar!: T;
来检索该元素。然而,初学者文档没有直接说明它是ElementRef
:它只在API中提到了这一点(并使用了术语"selector",这让我以为它是CSS选择器)。
它只是起作用,因为ElementRef
包含一个nativeElement
(DOM元素)。hashedId
就是这个东西(API将其称为选择器):
<tag #hashedId/>
在我的情况下,整个模板中的hashedId
被称为HTMLDivElement
(一个Element
)。
我写了这个:
@ViewChild('containerElement')
private containerElement!: Element;
// ...
ngAfterViewInit(): void {
console.log(this.containerElement);
}
即使在IDE中,我没有编译时错误。并且它在控制台记录了一个ElementRef
。我知道这是因为TypeScript不是一种强类型语言,而是映射到无类型的JavaScript,但我以为Angular会通过自己的构建系统自行纠正这个问题?
@ViewChild('containerElement')
private containerElement!: ElementRef;
英文:
My use-case is getting the bounding client rect internally and use it to position a viewport-relative container (a context menu).
Angular allows you to use @ViewChild('hashedId') someVar!: T;
to retrieve the element. However, the beginner documentation didn't tell it was an ElementRef
directly: it only tells that in the API (and uses the term "selector", which made me think it was the CSS selector).
It just works, because ElementRef
contains a nativeElement
(the DOM element). The hashedId
is that thing (which the API referred to as selector):
<tag #hashedId/>
In my case, hashedId
, within the entire template, was said to be a HTMLDivElement
(an Element
).
I wrote this:
@ViewChild('containerElement')
private containerElement!: Element;
// ...
ngAfterViewInit(): void {
console.log(this.containerElement);
}
I got no compile-time error even in the IDE. And it logged an ElementRef
at the console. I know that's because TypeScript isn't a sound language and maps to untyped JavaScript, but I thought Angular would correct this by itself with its own build system?
@ViewChild('containerElement')
private containerElement!: ElementRef;
答案1
得分: 1
装饰器不受变量类型的限制。
这就是为什么它不能“映射”到正确的类型。
这是你在使用Angular时需要知道的东西(尽管确实在文档中有提到)。
通常,你会记录变量并获取其类型,这是了解类型的简单方法。
如果你认为Angular有可能“映射”到正确的类型,可以尝试在他们的存储库上提出一个功能请求(甚至一个拉取请求?)。
英文:
The decorator is not bound to the type of the variable.
That's why it doesn't "map" to the correct type.
This is something you "need" to know when you use angular (although it is indeed in the documentation).
Usually, you log the variable and it gives its type, that's the easy way to know it.
If you think it's possible for angular to "map" to the correct type, try making a feature request (or even a pull request ?) on their repo !
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论