born2net
born2net

Reputation: 24953

In angular2, advantage of using zone.run vs changeDetecotor.markForCheck()

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?

Upvotes: 7

Views: 2420

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657338

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

Upvotes: 5

Related Questions