Search code examples
angularmutation-observers

How does Angular modify the DOM?


Imagine this template...

<ul>
    <li *ngFor="random"></li>
</ul>

...and a MutationObserver "listening" to its changes:

observer.observe(this.el, { characterData: true, subtree: true });

Now every time this template renders, the observer reacts correctly. But it does not, when I modify the content "by hand":

this.el.innerHTML = "<li>Another item</li>";

This is probably because Angular has much more clever ways to modify the DOM.

But just how exactly does Angular do it - in one line of code? Especially that "characterData" changes are getting triggered?


Solution

  • As @wOxxOm said if you use characterData: true option then the changes will be only triggered if you assign to an element's text node's nodeValue

    Angular uses #comment node for embedded views.

    enter image description here

    And angular assigns some meta information to this node

    enter image description here

    which causes the changes in MutationObserver to be triggered.