Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get DOM element which is a component in Angular

Tags:

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.

My HTML template contains component:

<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. Why is that happening?

like image 534
TheOpti Avatar asked Aug 18 '17 15:08

TheOpti


2 Answers

You can specify what you want using the read parameter:

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

This way you get the ElementRef and can use this.sidenav.nativeElement like mentioned by @joshrathke

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

like image 84
Günter Zöchbauer Avatar answered Nov 15 '22 10:11

Günter Zöchbauer


Edit

In order for this to work, you need to implement @Günter Zöchbauer suggestion for extracting the component using ViewChild with read.

Original Answer

You need to use the nativeElement property of the ElementRef object. You'll find your DOM Representation there. 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.

console.log(this.sidenav.nativeElement);
like image 37
joshrathke Avatar answered Nov 15 '22 11:11

joshrathke