Evening talk

Change Detection

Root

Header

Footer

ItemList

Item

Item

Page Layout

Come to Lecture

Understand CD

Data model

TaskList: [
  {
    id: 123,
    description: 'Come to Lecture',
    isImportant: true,
    isDone: true
  },
  {
    id: 456,
    description: 'Understand CD',
    isImportant: true,
    isDone: false
  },
  ...
]

Change Flow

Model

DOM

Component

Change Flow

Application State Update

View State Propagation

(after code finished)

(user interaction / browser event)

Change Detection Flow

(Change Detection Tree)

<parent>

      <child></child>

</parent>

Change Detection Complexity

Change Detection Time = C * N

C - time to check one binding

N - amount of bindings

Compilation

JIT

AOT

( just in time )

( ahead of time )

$ ng serve

$ ng build
$ ng serve --aot

$ ng build --prod

AOT: pros & cons

Pros

Cons

  • Checking error in template
  • Smaller bundle size
  • Faster initial load
  • Increasing build time (significantly)
  • Really bad in a big application (in dev mode)
  • TS restrictions (it's different for dev / prod)

AOT: conslusion

  • Compiles on building phase
  • Checks error in templates
  • Good practice for production

Reducing amount of nodes

Reducing amount of nodes

@Component({
  ...,
  changeDetection: ChangeDetectionStrategy.OnPush,
  ...
})

+ Immutable objects

ChangeDetectorRef

constructor(private ref: ChangeDetectorRef) {
    ...
}

Helps to control change detection behavior of current component

ChangeDetectorRef

  • markForCheck(): void
  • detach(): void
  • reattach(): void
  • detectChanges(): void
  • checkNoChanges(): void

Methods:

zone.js

  • User interaction

  • Server communication

  • Timer event

Models may be changed by:

any Async action

Async action

zone.js

Change Detection

zone.js

constructor (private ngZone: NgZone) {}

public processOutside() {
    this.ngZone.runOutsideAngular( () => {
        // do some stuff
    });
}

public goBack(someFunction) {
    this.ngZone.run(someFunction);
}

Links:

Change Detection

By Anton Bely

Change Detection

  • 1,658