TimTheEnchanter
TimTheEnchanter

Reputation: 3671

Angular direct DOM access?

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

  1. Simply states ElementRef.nativeElement is bad, don't use it, but doesn't offer much in the way of current, valid alternatives.
  2. Is old, still talking a lot about renderer being deprecated and other beta issues.
  3. Covers a very specific use case and is not particularly applicable outside that use case

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:

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.

Upvotes: 6

Views: 1187

Answers (1)

Max Koretskyi
Max Koretskyi

Reputation: 105499

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.

Upvotes: 2

Related Questions