SergeW
SergeW

Reputation: 23

Angular : I need help on "change detection"

I'm working on an angular project, and I need to master change detection so as to make my project usable.

Here is a minimal repro : https://stackblitz.com/edit/angular-3py5bh

<div *ngIf="timeleft$ | async as timeleft"> //countdown (rxjs)
    {{timeleft}}
</div>
<hello></hello> // simulated intensive function

So, basically, I have a main component with a countdown, that refreshes every 0.01s. In this component I have an embedded "hello" component, that includes (in real project) quite intense computations. I simulated these intense computations with a "slow function".

Problem : every time the countdown refreshes (so 100 times/second), the Hello component is refreshed as well, and the "slow function" is called...

As a result, the countdown display is broken (too slow) !!!

I know the answer relies on "change detection", but I'm too new to handle it well. That's why I'm asking for your help !

Thanks a lot !!! Serge

Upvotes: 0

Views: 151

Answers (1)

Kyle Anderson
Kyle Anderson

Reputation: 754

I would try setting changeDetection: ChangeDetectionStrategy.OnPush on your 'slow' component. This fixes your stackblitz see below:

import { ChangeDetectionStrategy, Component, Input} from '@angular/core';

@Component({
  selector: 'hello',
  template: `<h1>Result : {{mySlowFunction(8)}}!</h1>`,
  styles: [`h1 { font-family: Lato; }`],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class HelloComponent {
  @Input() name: string;

mySlowFunction(baseNumber) {
    let result = 0; 
    for (var i = Math.pow(baseNumber, 7); i >= 0; i--) {        
        result += Math.atan(i) * Math.tan(i) ;
    };
  return result;

}

}

Upvotes: 1

Related Questions