gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:13:15 26 4
gpt4 key购买 nike

主要区别是什么

<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

我正在维护的应用程序在 ngStyle 上调用这些函数 getStyle 很多次(大概 5k 次)。我目前正在将样式计算更改为指令,因为我认为它更干净。

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

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

谢谢

最佳答案

必须尽可能避免属性绑定(bind)中的函数调用,这是因为在每个 Angular 变化检测周期都会调用该函数,即使在组件 View 上更改了不相关的属性也是如此。由于这个原因,绑定(bind)到 [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

关于angular - ngStyle 与指令调用函数之间的性能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56453858/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com