Angular2指令:如何检测DOM更改 [英] Angular2 Directive: How to detect DOM changes

查看:158
本文介绍了Angular2指令:如何检测DOM更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



因此,格式可能是:

 < body my-skrollr> 
< / body>

然而,为了实现这一点,我需要能够检测到孩子中DOM的变化元素下面的包含标签(在这种情况下,< body>),所以我可以调用skrollr.init()。并更新库以处理新的内容。



有没有一个直接的方法来做到这一点,我不知道,或者我正在接近这个错误? / p>

解决方案

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


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?

解决方案

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

这篇关于Angular2指令:如何检测DOM更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆