微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

[Angular] Angular Custom Change Detection with ChangeDetectorRef

Each component has its own ChangeDetectorRef,and we can inject ChangeDetectorRef into constructor:

export class ChildComponent implements OnInit {

  constructor(
    private cdr: ChangeDetectorRef
  )

 

For example if you have a huge list can be updated in real time though some real time database.

Update in real time is really expensive for huge list. 

 

We have build a custom change detector,for example,update every 5 seconds,to check changes,to do that,we need to two things,

1. disable default change detector

2. Check for changes every 5 seconds.

import { Component,OnInit,ChangeDetectorRef } from @angular/core;
import { ListService } from ./list.service;

@Component({
  selector: app-child,templateUrl: ./child.component.html,styleUrls: [./child.component.css]
})
export class ChildComponent implements OnInit {

  constructor(
    private cdr: ChangeDetectorRef,private dataProvider: ListService
  ) { 
    // disable default change detector
    cdr.detach();
    // Now every 5second,do a check for its child tree
    setInterval(() => { this.cdr.detectChanges(); },5000);
  }

  ngOnInit() {
  }

}

 

There is another API: reattach() which uses for reset to default Angular change dectctor.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐