16

I have google maps which triggers 100+ times per second change detection. how to disable change detection for this.

Click here for map preview

it will be even worse when using mouseover event.

ngDoCheck() {
  console.log('do check', this.i++);
}
Inzimam Tariq IT
  • 6,548
  • 8
  • 42
  • 69
tarmo
  • 325
  • 1
  • 2
  • 7
  • I don't think this is related to 3rd party directived. Angular2 runs change detection after each event. You ca set `ChangeDetectionStrategy.OnPush` to do manual change detection. – Günter Zöchbauer Aug 17 '16 at 12:25

2 Answers2

33

I had the same issue, try injecting the NgZone class on your component constructor

constructor(private zone: NgZone) {

)

then, use the runOutsideAngular method from NgZone to put in a callback the draw method from google charts, do something like this.

this.zone.runOutsideAngular(() => {
    var chart = new google.visualization.PieChart(nativeElement);
    chart.draw(dataTable, options);
})

This make the executed code don't fire angular detection changes. Apply this for each chart you make. I hope find this helpful.

Thanks to this

  • Thanks. Used this on my company website canvas animation https://github.com/aviabird/website/blob/master/src/app/shared/services/canvas-animate.service.ts – pkrawat1 Oct 01 '17 at 03:05
14

Another option to temporary disable change detection ChangeDetectorRef

enabled = true;  
constructor(private ref: ChangeDetectorRef)

toggleChangeDetection() {
  if (this.enabled) 
  {
    this.enabled = false;
    this.ref.detach();
  }
  else {
    this.enabled = true;
    this.ref.reattach();
}
  • 1
    It's important to understand that this will only detect change detection on "this" component. So all other components would need to do this. It's easier of course to make that one "problematic" component not trigger the changeDetection, instead of disabling change detection on all other components, I think. – Sebastian Jul 07 '20 at 15:08