如何在组件的类中获取模板中的DOM元素?

huangapple go评论55阅读模式
英文:

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(&#39;hashedId&#39;) 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):

&lt;tag #hashedId/&gt;

In my case, hashedId, within the entire template, was said to be a HTMLDivElement (an Element).

I wrote this:

@ViewChild(&#39;containerElement&#39;)
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(&#39;containerElement&#39;)
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 !

huangapple
  • 本文由 发表于 2023年7月24日 00:24:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76749265.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定