Tuesday, March 28, 2017

How not to do change detection management in Angular 4.

Consider this official example:

@Component({
   selector: 'cmp',
   changeDetection: ChangeDetectionStrategy.OnPush,
   template: `Number of ticks: {{numberOfTicks}}`
})
class Cmp {
   numberOfTicks = 0;
   constructor(ref: ChangeDetectorRef) {
      setInterval(() => {
         this.numberOfTicks++;
         ref.markForCheck();
      }, 1000);
   }
}
@Component({
   selector: 'app',
   changeDetection: ChangeDetectionStrategy.OnPush,
   template: `
      
   `,
})
class App {
}

 
 

Alright, first of all, the above leaves out the import statement you'll need if you make a .ts file, but that's not the biggest thing. Have an import statement like so:

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

 
 

The biggest thing is that you don't want to spin an interval. You only want to kick off change detection when something changes, not once a second as the approach above in effect has you doing the exact same time as having a ChangeDetectionStrategy of Default except that it's a little bit slowed down. The fact that it repeats when possibility unneeded is no good. The example of making a number count upwards which is the first thing everyone learned to do in BASIC is NOT real world code. You are not a child and it's not the 80s. The IBM PC Junior you had is long gone. Instead, you will want to turn all the watchers off until you really need them, say on a button click. If something has to happen after a user action when a dependency fills in asynchronously then things get a bit more tricky. Hand in promises using the Promise API which can trigger change detection strategy from a .done() If you're handing a function in from outside the component, you may have a .then on the function at the outside and then do a .then off of the function inside the component too when you call it to do other .then stuff. One does not overstamp the other. They both run. This is better than spinning an interval to react when the .then occurs outside the component at the code handed in.

 
 

Addendum 4/13/2017: I'm realizing there is a Russian doll thing going on with the .then stuff of the Promise API not unlike Middleware in .NET Core. If a function calls a function while having a .then and the function called has a .then, expect the inner function's .then to run and then the outer function's .then.

No comments:

Post a Comment