I know this has been asked a zillion times and received answers in many cases. I believe I've read most of them. Unfortunately, everything I can find on this
ElementRef.nativeElement
is bad, don't use it, but doesn't offer much in the way of current, valid alternatives. So I'm trying to wrap my head around where things stand currently. v5 was recently released and things have in general stabilized across many fronts. Current is important - we're getting ready to start a brand new project with no legacy anything behind it, so we want to start as clean as possible.
Is it safe to take the following approaches:
nativeElement
property is safe. Almost every directive example in the official docs does thisnativeElement
in conjunction with Renderer2
(for example
this.renderer2.setStyle(elm.nativeElement, 'background-color', 'red');
) is OK because Renderer2 somehow magically makes it work (Renderer2 is another thing I can't find really good docs on how it performs this magic)nativeElement
is always OK if you are not and will never be, doing server side rendering or using web workers (please disregard the fact that we can't predict the future)@ViewChild('myElement')
, @ViewChildren('myElement') myElements: QueryList<ElementRef>;
, or similar with @ContentChild/ren('myElement',{read:ElementRef })
to get and use the element(s)nativeElement
before trying to use it.Note that in most of these cases, we're still using nativeElement
they just vary in how we access it. To me, that means nativeElement
itself isn't a problem, it's all in how you get it and use it.
Am I missing anything? Any problems with any of the above? I'm trying to get fact, not opinion, so any links to official docs, or even really good, current blog posts would be great.
Thanks.
Generally you should prefer the Renderer2
service when you need to change DOM element properties. But do not use the Renderer2
to change DOM hierarchy. Instead use the templating technique and view containers.
Using nativeElement is always OK if you are not and will never be, doing server side rendering or using web workers (please disregard the fact that we can't predict the future)
Yes. Or mobile devices.
To me, that means nativeElement itself isn't a problem, it's all in how you get it and use it.
Different platforms can implement access to DOM elements in different ways. For example, the Renderer2
service inside the webworker, instead of calling native DOM methods (which doesn't exist inside the webworker) simply transmits the message to main UI thread. If you use nativeElement
directly, you get an error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With