The ability to reply to discussions is limited to PRO members. Want to join in the discussion? Click here to subscribe now.

Manipulate and Access DOM Elements with Angular 2 Renderer

Manipulate and Access DOM Elements with Angular 2 Renderer

3:46
The Angular 2 renderer allows you to safely use elements created in your template regardless of the platform you’re working on. It’s important to remember that your components could easily be used inside a ServiceWorker or other platform, so you should always rely on the renderer to keep your DOM access safe.
Watch this lesson now
Avatar
egghead.io

The Angular 2 renderer allows you to safely use elements created in your template regardless of the platform you’re working on. It’s important to remember that your components could easily be used inside a ServiceWorker or other platform, so you should always rely on the renderer to keep your DOM access safe.

Avatar
christiannwamba

Hi John. I was wondering what makes direct access to the DOM unsafe. Tried digging the docs to see a vivid explanation but didn't find any. Maybe am missing something about how Angular handles rendering.

Avatar
Daniel

Great course! But I found one thing confusing throughout: often, you use variable and ref names that match tag names and the like in ways that makes things less clear. For example, in this video, you create an input tag, give it the ref name of 'input', then assign it to a var with, ViewChild again naming the variable 'input'. While you say that you could name it anything, naming it anything other than exactly the name of the tag (myInput?) would have made it clearer what you were accessing, and how to do so.

Avatar
Brian

This sounds swell and all in this little demo, until you find out that Angular 2 doesn't have a great DOM abstraction, so if you want to get something like offsetHeight, which is a property getter, you can't do it without nativeElement. I suppose you could do getBoundingClientRect(), but it's frustrating that the DOM abstractions are so thin.

Edit: this.renderer.invokeElementMethod(this.ref.nativeElement, 'getBoundingClientRect') is not only a hilariously unwieldy abstraction, but it doesn't even work.

I've been using Angular for 5+ years, and I'm really annoyed they dropped the ball on this when React has shown such a clear example of why this abstraction is so useful.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?