ngStyle 与指令上调用函数之间的性能

Raf*_*ade 2 angular-directive angular angular5

主要区别是什么

<p [ngStyle]="getStyle()"> 
// getStyle returns a string like "color:blue" and some other attributes
Run Code Online (Sandbox Code Playgroud)

<p appStyle [status]="myStatus">
//directive get myStatus as a input and calculate the style of the tag
Run Code Online (Sandbox Code Playgroud)

我正在做维修电话,这些功能的应用getStylengStyle有很多(可能5K次)。我目前正在将样式计算更改为指令,因为我认为它更干净。

但是不知道对性能有多大影响。我怎么能测量它?

另一个问题,是否有文档/教程/书籍可以解释这样的事情?

谢谢

use*_*584 7

必须尽可能避免在属性绑定中调用函数,这是因为即使在组件视图上更改了不相关的属性,也会在每个角度变化检测周期调用该函数。由于这个原因,绑定到 [ngStyle] 的“getStyle()”方法被多次调用 [甚至超过预期]。您的第二个代码方法 [指令] 一比功能一要好得多。在指令方法中,当您的有界输入 PROPERTY 发生更改时,只会执行与您的底层指令的输入属性更改相关的代码。您也可以通过使用 ChangeDetectionStrtegy.OnPush [ https://blog.angular-university.io/onpush-change-detection-how-it-works/]来提高性能. 此外,如果您将数据从数据转换为演示文稿,则应使用 Angular 管道。因为管道是记忆的[即管道仅在输入改变时评估]。

请参阅以下文章-

https://blog.angularindepth.com/tiny-angular-pipe-to-make-any-function-memoizable-f6c8fa917f2f https://blog.angularindepth.com/the-essential-difference-between-pure-and-impure -pipes-and-why-that-matters-999818aa068