I am facing a frustrating performance issue.
Within my component, I have implemented ngStyle
and I would rather not rewrite it. However, every time I interact with random input
fields on the same page (even from another component), the ngStyle
recalculates slowly.
For example, I want to create a table displaying the product of two numbers with dynamic background colors:
<section>
<div class="row"
*ngFor="let row of rows">
<div class="col"
[ngStyle]="{'background-color': getBG(row*col)}"
*ngFor="let col of cols ">
{{row * col}}
</div>
</div>
</section>
However, when I add several input fields to the page:
<section>
<input type="text" [ngModel]="model1"/>
<input type="text"[ngModel]="model2"/>
<input type="text"[ngModel]="model3"/>
<input type="text"[ngModel]="model4"/>
<input type="text"[ngModel]="model5"/>
</section>
Each click on these inputs triggers a call to getBG()
, resulting in sluggish performance. This is evident even if the function simply returns a string without any complex calculations.
To see this issue in action, check out the Example at StackBlitz. Open the console and try clicking swiftly among different input fields or entering values - the responsiveness is notably lacking.
UPD1: My scenario involves a more intricate setup, and I already employ ChangeDetectionStrategy.OnPush
. Even binding ngStyle
directly to a value instead of a function does not significantly improve performance, as it remains slow and introduces complexity. Ideally, I seek a way to instruct ngStyle
not to recalculate unless explicitly requested. Perhaps leveraging ChangeDetectorRef.detach()
could provide some assistance.