Should use ChangeDetectionStrategy.OnPush for eveything?

后端 未结 3 1784
感动是毒
感动是毒 2021-01-18 09:41

As the title says: I\'m working on a very big project and in few components I\'ve used ChangeDetectionStrategy.OnPush to avoid bad performances. I was wondering

相关标签:
3条回答
  • 2021-01-18 10:18

    ChangeDetectionStrategy.OnPush tells Angular that the component only depends on its @Inputs() and needs to be checked only in the following cases:

    The Input reference changes.

    An event originated from the component or one of its children.

    We run change detection explicitly.

    So it depends from your component's content and what you are trying to achieve with it. For example if you are using async pipe for your subscriptions, your component doesn't need ChangeDetectionStrategy.OnPush, because async will do the job automatically. If your component big and uses a lot of data changes, it should contain OnPush strategy, because it will increase your performance, so your whole component code will not run on every changes. If your component small and has only a few properties and methods, or it doesn't contain any subscription or @Input's, or doesn't do any data changes that will happen often, you don't need ChangeDetectionStrategy.OnPush

    0 讨论(0)
  • 2021-01-18 10:27

    Especially with very big projects, the OnPush strategy is recommended to decrease the change detection process that it is a very expensive operation.

    With inherited projects, the recommendation is to start applying the OnPush strategy from the leaf components and check that everything is still working.

    Only at this point, follow the ancestors and go up one level at time to the root. In the end the overall performance will benefit.

    Here there is a very good article about change detection in Angular.

    0 讨论(0)
  • 2021-01-18 10:30

    NO NO and NO. Angular already introduces a lot of complexity to any code, but it gives you back a lot of features, such as change detection. If you remove change detection from Angular, then you are getting all the bad without the good. If you don't have thousands of components in your page, then you won't notice any perceptible improvements in removing change detection.

    So:

    • Always use change detection
    • Detach change detection in particular cases, where checking objects deeply can decrease performance in a considerable way
    0 讨论(0)
提交回复
热议问题