Angular2 Directive: How to detect DOM changes

陌路散爱 提交于 2019-12-18 03:55:34

问题


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?


回答1:


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);
  }
}


来源:https://stackoverflow.com/questions/36130393/angular2-directive-how-to-detect-dom-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!