简体   繁体   English

获取DOM元素,它是Angular中的一个组件

[英]Get DOM element which is a component in Angular

I read some answers already here, such as this , but my problem is slightly different. 我已经在这里读了一些答案,比如这个 ,但我的问题略有不同。 I want to get component as a DOM element so that I can add/remove some CSS classes on it. 我想将组件作为DOM元素,以便我可以在其上添加/删除一些CSS类。

My HTML template contains component: 我的HTML模板包含组件:

<sidenav-menu #sidenav class="app__sidenav"></sidenav-menu>

And my class contains a reference to it: 我的类包含对它的引用:

@ViewChild('sidenav') sidenav: ElementRef;

But when I log this.sidenav in one of my functions, I see that it is a representation of a class of Sidenav component, not its DOM representation. 但是当我在我的一个函数中记录this.sidenav时,我发现它是一个Sidenav组件类的表示,而不是它的DOM表示。 Why is that happening? 为什么会这样?

You can specify what you want using the read parameter: 您可以使用read参数指定所需内容:

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

This way you get the ElementRef and can use this.sidenav.nativeElement like mentioned by @joshrathke 这样你就得到了ElementRef并且可以使用像this.sidenav.nativeElement提到的this.sidenav.nativeElement

or (for other use cases) 或(对于其他用例)

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

My answer to the question you liked to also mentions this read parameter https://stackoverflow.com/a/35209681/217408 我的回答对你喜欢的问题也提到了这一点read参数https://stackoverflow.com/a/35209681/217408

Edit 编辑

In order for this to work, you need to implement @Günter Zöchbauer suggestion for extracting the component using ViewChild with read . 为了实现这一点,您需要实现@GünterZöchbauer建议,使用ViewChild read组件。

Original Answer 原始答案

You need to use the nativeElement property of the ElementRef object. 您需要使用ElementRef对象的nativeElement属性。 You'll find your DOM Representation there. 你会在那里找到你的DOM表示。 Its also what exposes the DOM element and allows you to call traditional methods on it as if it was a DOM element in vanilla javascript or jQuery. 它也暴露了DOM元素,并允许您在其上调用传统方法,就好像它是vanilla javascript或jQuery中的DOM元素一样。

console.log(this.sidenav.nativeElement);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM