最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Renderer2, ViewChild and ElementRef. Why do we needuse such things in Angular? - Stack Overflow

programmeradmin1浏览0评论

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!

Share Improve this question edited Apr 16, 2018 at 2:29 DongBin Kim asked Jan 20, 2018 at 4:47 DongBin KimDongBin Kim 1,9897 gold badges28 silver badges45 bronze badges 3
  • 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
Add a ment  | 

2 Answers 2

Reset to default 6

When 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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论