金木编程

公众号:金木编程

导航

Angular 产品开发中 OnPush 策略最佳实践

背景
在Angular产品开发中,随着功能的增多,项目的性能会变慢。其中一个重要原因就是每次model数据改变时,都会触发大量组件的变更检测。为了解决问题,我们可以应用Onpush策略。

方案
本文参考了大量理论资料,并结合实际项目提出了应用OnPush策略的最佳实践,供读者参考。

最佳实践

1. 尽量在所有组件中应用OnPush策略。
https://ionic.io/enterprise-guide/angular
2. 进行变更检测一定要有原因,不要随便进行变更检测。
https://netbasal.com/a-comprehensive-guide-to-angular-onpush-change-detection-strategy-5bac493074a4
https://www.learnfk.com/question/angular/41364386.html
3. 对一个大型Angular项目应用OnPush策略时,应该先从叶子节点开始,保证一切工作正常后,再逐级向上应用OnPush策略,直到根节点组件。
https://stackoverflow.com/questions/52979543/should-i-always-use-changedetectionstrategy-onpush
4. 没有input参数的组件,也可以应用OnPush策略。
https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/components/cdk/overflow/overflow-container.component.ts https://git.advent.com/projects/TAM/repos/tamalenextgen2/browse/tamaleweb/src/app/widgets/select-window/select-window.component.ts
5. 与值类型input参数不同,引用类型input参数需要为它创建一个新的对象,才能触发OnPush变更检测。
https://zhuanlan.zhihu.com/p/96486260 https://git.advent.com/projects/TAM/repos/tamalenextgen2/browse/tamaleweb/src/app/widgets/html-container/html-container.component.ts https://git.advent.com/projects/TAM/repos/tamalenextgen2/browse/tamaleweb/src/app/widgets/entity-dropdown-item
6. 如果一个组件仅仅依赖于它的input属性,并且input属性是observable,那么应该使用async管道来标注该组件需要进行变更检测。
https://zhuanlan.zhihu.com/p/96486260 https://git.advent.com/projects/TAM/repos/tamalenextgen2/browse/tamaleweb/src/app/widgets/smart-icon/smart-icon.component.ts
7. 为了防止变更检测错误,最好使用不可变对象(immutable objects)和列表(lists)作为input参数在来构建OnPush策略应用程序。
https://mokkapps.de/blog/the-last-guide-for-angular-change-detection-you-will-ever-need/ https://git.advent.com/projects/TAM/repos/tamalenextgen2/browse/tamaleweb/src/app/widgets/timeline/timeline.component.ts
8. 为了提高性能,可以从 Angular 更改检测周期中分离组件及其子组件。 为此,我们可以使用 ChangeDetectorRef.detach() 方法。
https://timdeschryver.dev/blog/help-angular-to-make-your-application-faster#detach-components-from-the-change-detection
9. 确保从包括 XHR 调用、Timer 和 Event 在内的每个方法中调用 detectChanges 方法。 可以假设 detectChanges 方法负责实际的更改检测。
https://medium.com/ngconf/simplified-angular-change-detection-e74809ff804d
10. 可以采用lighthouse来记录应用OnPush策略后web页面性能提升
https://chrome.google.com/webstore/detail/lighthouse/blipmdconlkpinefehnmjammfjpmpbjk?hl=zh-cn

OnPush案例
1. NG-ZORRO
https://github.com/NG-ZORRO/ng-zorro-antd

 

 2.Angular Material

https://github.com/angular/components/tree/master/src/material
Internationalized and accessible components for everyone. Well tested to ensure performance and reliability.

posted on 2022-08-30 22:03  金木杂谈  阅读(53)  评论(0编辑  收藏  举报