In Angular2, why are there 2 times check for content and view after setTimeout?

前端 未结 1 1265
陌清茗
陌清茗 2020-12-11 10:18

Here\'s my code

@Component({
  template: `

Hello from A

相关标签:
1条回答
  • 2020-12-11 10:43

    Angular utilizes zones to know when an event is fully processed by patching some async APIs like (addEventHandler, setTimeout, ...) and then runs change detection after each event.

    In dev mode Angular does an additional change detection run, just after the first one. Because there was no event in between, no change should have happened.

    If the model still changed, Angular considers this to be a possible bug.

    Possible causes:

    • A field, getter or function the view binds to returns a different instance each time, which is recognized as change.
      This is often with functions that return a filtered subrange of an array. This subrange should be assigned to a field and return the same cached instance unless a filter criteria has changed.
      Angular only compares identity of the previously and currently returned array and ignores whether the content of the array (or other objects) is still the same.

    • Code that was invoked by an event that was not registered within Angulars patched zone caused a model change.
      This is usually caused by 3rd-party libraries that aren't initialized fronm within Angular. Either initialize them within Angular if possible, or notify Angular about the change (Triggering Angular2 change detection manually)

    In production mode Angular just checks once and ignores possible side effects.

    0 讨论(0)
提交回复
热议问题