I'm quite new to Angular and I've discovered that there's something like Renderer2
, ViewChild
and ElementRef
for the sake of handling DOM rather than accessing it directly. And the articles I've e across say that manipulating DOM directly is a bad idea so we should use those Angular offering wrapper, service whatever it is. So it gets me wondering, in what point is handling DOM directly a bad idea? Any insight would be appreciate!
I'm quite new to Angular and I've discovered that there's something like Renderer2
, ViewChild
and ElementRef
for the sake of handling DOM rather than accessing it directly. And the articles I've e across say that manipulating DOM directly is a bad idea so we should use those Angular offering wrapper, service whatever it is. So it gets me wondering, in what point is handling DOM directly a bad idea? Any insight would be appreciate!
-
1
I would say the primary reason is that Angular re-renders the view with it's change-detection cycle.So, changes (ideally) should happen in a way that's detectable by Angular. That said - there are some examples of direct manipulation of DOM in Angular that work fine, for example styling via a Directive (see Attribute Directives and search for
nativeElement
). You just have to know that what you change on DOM does not affect the change detection mechanism. – Richard Matsen Commented Jan 20, 2018 at 6:21 - @RichardMatsen as far as I know, el(ElementRef type).nativeElement indicates/points the related DOM itself. So in my knowledge, manipulating DOM using nativeElement seems not that different from accessing DOM directly. What am I missing here? – DongBin Kim Commented Jan 23, 2018 at 4:07
-
You are missing nothing.
nativeElement
gives you access to the DOM from ElementRef or ViewChild. – Richard Matsen Commented Jan 23, 2018 at 4:11
2 Answers
Reset to default 6When we access the native element directly we are giving up on Angular’s DOM abstraction and miss out on the opportunity to be able to execute also in none-DOM environments such as native mobile, native desktop, web worker or server-side rendering.
Remember that Angular is a platform, and the browser is just one option for where we can render our app.
So what you do is to give this responsibility to these classes.
Handling the dom directly in Angular is a "bad idea" when you need server-rendering or using a webworker where it does not work.It also makes creating unit testing easier as you are not manipulating the dom.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745622052a4636578.html
评论列表(0条)