typescript Angular2 指令:如何检测 DOM 更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36130393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:21:46  来源:igfitidea点击:

Angular2 Directive: How to detect DOM changes

javascriptdomtypescriptangularskrollr

提问by Tom Mettam

I want to implement Skrollr as an Angular2 attribute directive.

我想将 Skrollr 实现为 Angular2 属性指令。

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.

但是,为了实现这一点,我需要能够检测包含标记(在本例中为 <body>)下方的子元素中 DOM 的更改,以便我可以调用 skrollr.init().refresh() ; 并更新库以使用新内容。

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

是否有一种我不知道的直接方法,或者我是否错误地处理了这个问题?

回答by Günter Z?chbauer

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

Angular 没有为此提供内置的东西。您可以使用MutationObserver来检测 DOM 更改。

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