6

I am wondering what's the advantage or disadvantage of using one over other:

 constructor(private app:ApplicationRef, private ref:ChangeDetectorRef) {
    this.ref.markForCheck();
    // OR
    this.ref.detectChanges()  
    // will do same thing?
 ...

vs

zone.run

(() => doSomething())
    ...

vs

  app.tick();

they all essentially will mark the component for checking and updates / redraw the UI.

I know app.tick() will do it for the entire app, but in my tests it didn't actually force the UI to update.

zone.run and markforCheck both force the UI to update on the next zone cycle check, so why use one over the other?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
born2net
  • 24,129
  • 22
  • 65
  • 104

1 Answers1

4

If you run code that only affects the current component, like

someServiceThatRunsOutsideZone.getData()
.subscribe(data => {
  this.data = data;
  this.ref.markForCheck();
});

this.ref.markForCheck() is just fine.

If you do for example this.router.navigateXxx(...) outside Angulars zone then it's hard to know if this.ref.markForCheck() will cover all elements that might get their state changed by this rather complex operation.

Also if this.router.navigateXxx(...) invokes some async calls, your markForCheck will be run before these async calls are completed and will not invoke change detection at the end as it is probably necessary.

With

this.zone.run(() => this.router.navigateXxx(...))

it doesn't matter because this.router.navigateXxx() and all code that is invoked by that call (sync and async) will run inside Angulars zone and use its patched API.

I don't know about the exact difference between app.tick and markForCheck but app.tick also does have the disadvantage explained above for markForCheck

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    got it... that makes sense, this.zone.run is more powerful as you have future operations within the zone to be detected as well... got it, tx as always! – born2net 20 mins ago – born2net Jun 05 '16 at 16:14