⚠️ This lesson is retired and might contain outdated information.

Manipulate and Access DOM Elements with Angular 2 Renderer

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 2 months ago

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.

Christian Nwamba
Christian Nwamba
~ 8 years ago

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.

Daniel Karp
Daniel Karp
~ 7 years ago

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.

Brian
Brian
~ 7 years ago

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.

iUsemws
iUsemws
~ 7 years ago

https://github.com/angular/angular/issues/15674

iUsemws
iUsemws
~ 7 years ago

i meant to post: https://github.com/angular/angular/issues/13818

jeronimo
jeronimo
~ 7 years ago

Renderer is deprecated, you should use Renderer2

https://stackoverflow.com/questions/43392607/now-that-renderer-is-deprecated-as-a-favor-for-renderer2-is-there-an-alternativ

Admin
Admin
~ 7 years ago

I've found that this.input.nativeElement.focus() doesn't work... Can be it possible because of I use Angular4?

coderty
coderty
~ 4 years ago

This is the way it worked for me (Angular9 and using Render2):

this.renderer.selectRootElement(this.input.nativeElement).focus();

Markdown supported.
Become a member to join the discussionEnroll Today