Practices - Do you avoid directly modifying the DOM from your components?
  v6.0 Posted at 23/12/2019 5:04 PM by Gabriel George

​U​sing DOM is fine, but manipulating DOM directly in your component is not. ​With the introduction of Angular, 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 Angular application can be ported to another target by simply replacing the template and template loader.  Projects such as Angular React Native Renderer leverages this to allow native mobile app development in Angular.​​

  • 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 Angular should read these fields to draw itself.

This component manipulates the DOM directly to show and hide the menu
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: