I have a very stupid performance issue.
I have a component that uses ngStyle
, and I'd prefer to not rewrite it. But each time I click random input
on the same page (even from another component), ngStyle
recalculates (and do it pretty slow).
Let's say I want to have a table of multiply with dynamic background:
<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>
Then on the same page I want to add several inputs for a some reason:
<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>
Now each time I click on one of those inputs - getBG()
will be called. And even if that function just return a string without any calculations - it's still super slow
Example at StackBlitz - just open consomle and try to click swiftly among different input fields, or enter a value. Even as a user I can see it's not responsive at all
UPD1: My real-world case much more complex. And already use ChangeDetectionStrategy.OnPush
. Binding ngStyle
to a value instead of function also doesn't help much - it faster but still slow (and produces a lot of complexity). What I want, it's probably a way to tell ngStyle
to not recalculate until I'll ask explicitly. Maybe ChangeDetectorRef.detach()
could help