Home
Do you avoid the DOM in your components?
  v2.0 Posted at 23/04/2016 8:30 AM by Tiago Araujo

W​ith the introduction of Angular2, there has been a big push in ensuring the DOM stays out of your JavaScript code.  It is designed in such a way that an existing angular2 application can be ported to another target by simple replacing the template and template loader.  Projects such as Angular2 React Native Renderer  leverages this to allow native mobile app development in Angular2. 

For this to work well, there has to be a clear separation between the component’s logic and the component’s view – which means avoiding using the DOM in your component’s code.  This gives a few further advantages:

  • Smaller component code making it easier to maintain
  • Faster running and easier to write unit tests
  • Easier for designers to get involved​

This means that the component's state must expose things that are useful to the template as public properties or fields, and the template should read these fields to draw itself.​

dom1.png
This component manipulates the DOM directly to show and hide the menu
dom2.png
This component sets component state, which the template can use.  It is simpler, more descriptive and easier to test

Related rules

    Do you feel this rule needs an update?

    If you want to be notified when this rule is updated, please enter your email address:

    Comments:

    Note: Social Media login for Yotpo is not working in IE or Safari, please use Chrome. We are waiting for Yotpo to fix it.