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.
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.
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.
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.
https://github.com/angular/angular/issues/15674
i meant to post: https://github.com/angular/angular/issues/13818
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
I've found that this.input.nativeElement.focus() doesn't work... Can be it possible because of I use Angular4?
This is the way it worked for me (Angular9 and using Render2):
this.renderer.selectRootElement(this.input.nativeElement).focus();