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

时间:2019-06-05 03:19:08

标签: angular angular5 angular-directive

的主要区别是什么
<p [ngStyle]="getStyle()"> 
// getStyle returns a string like "color:blue" and some other attributes

<p appStyle [status]="myStatus">
//directive get myStatus as a input and calculate the style of the tag

我正在维护的应用程序在getStyle上多次调用了这些功能ngStyle(大约五千次)。我目前正在将样式计算更改为指令,因为我认为它更干净。

但是我不知道它将对性能产生多大影响。我该如何测量?

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

谢谢

1 个答案:

答案 0 :(得分:3)

必须尽可能避免在属性绑定中进行函数调用,这是因为即使在组件视图上更改了不相关的属性,该函数也会在每个角度变化检测循环上调用。因此,绑定到[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