Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 Directive: How to detect DOM changes

Tags:

I want to implement Skrollr as an Angular2 attribute directive.

So, the format may be:

<body my-skrollr> </body> 

However, in order to implement this, I need to be able to detect changes in the DOM in child elements below the containing tag (in this case, <body>), so that I can call skrollr.init().refresh(); and update the library to work with the new content.

Is there a straightforward way of doing this that I'm not aware of, or am I approaching this incorrectly?

like image 538
Tom Mettam Avatar asked Mar 21 '16 11:03

Tom Mettam


People also ask

How do you know if DOM has changed?

“MutationObserver” is a Web API provided by modern browsers for detecting changes in the DOM. By using this API you can listen to changes in DOM, like added or removed nodes, attribute changes or changes in the text content of text nodes and make changes.

How to detect a change in Angular?

Change detection works by detecting common browser events like mouse clicks, HTTP requests, and other types of events, and deciding if the view of each component needs to be updated or not.

What is MutationObserver in angular?

The MutationObserver interface provides the ability to watch for changes being made to the DOM tree.

What is DOM in angular?

DOM stands for Document Object Model. AngularJS's directives are used to bind application data to the attributes of HTML DOM elements.


1 Answers

Angular does not provide something built-in for that purpose. You can use MutationObserver to detect DOM changes.

@Directive({   selector: '[my-skrollr]',   ... }) class MyComponent {   constructor(private elRef:ElementRef) {}    ngAfterViewInit() {     this.observer = new MutationObserver(mutations => {       mutations.forEach(function(mutation) {         console.log(mutation.type);       });        });     var config = { attributes: true, childList: true, characterData: true };      this.observer.observe(this.elRef.nativeElement, config);   } } 
like image 145
Günter Zöchbauer Avatar answered Oct 14 '22 20:10

Günter Zöchbauer