What is the main difference of
<p [ngStyle]="getStyle()">
// getStyle returns a string like "color:blue" and some other attributes
to
<p appStyle [status]="myStatus">
//directive get myStatus as a input and calculate the style of the tag
The application that I'm doing maintenance call these functions getStyle
on ngStyle
a lot (probably 5k times). I am currently changing the style calculation to directives, because I think its cleaner.
But I don't know how much it will affect performance. How could I measure it?
Another question, is there a document/tutorial/book that explain things like that?
Thanks
A function call in property binding must be avoided as much as possible, this is because the function is called on every angular change detection cycle even an unrelated property is changed on the component view. Because of this reason "getStyle()" method bound to [ngStyle] is called many many times [even more than expected].
Your second code approach [directive] one is far better than function one. In the directive approach when your bounded input PROPERTY is changed then only your underlying directive's input property change related code gets executed. Also you can enhance the performance by using ChangeDetectionStrtegy.OnPush [https://blog.angular-university.io/onpush-change-detection-how-it-works/].
Also, Angular pipe should be used in case you are transforming your data from data to presentation. Because pipes are memoized [i.e. Pipe evaluated only if the input is changed].
See the following articles -
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