【发布时间】:2019-07-16 15:00:10
【问题描述】:
我有一个非常愚蠢的性能问题。
我有一个使用ngStyle 的组件,我不想重写它。但是每次我在同一页面上单击随机input(甚至来自另一个组件),ngStyle 都会重新计算(而且速度很慢)。
假设我想要一张带有动态背景的乘法表:
<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>
然后出于某种原因,我想在同一页面上添加几个输入:
<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>
现在每次我点击这些输入之一 - getBG() 都会被调用。即使该函数只返回一个字符串而不进行任何计算 - 它仍然非常慢
Example at StackBlitz - 只需打开控制台并尝试在不同的输入字段之间快速单击,或输入一个值。即使作为用户,我也可以看到它根本没有响应
UPD1:我的真实案例要复杂得多。并且已经使用ChangeDetectionStrategy.OnPush。将ngStyle 绑定到一个值而不是函数也无济于事——它更快但仍然很慢(并且会产生很多复杂性)。我想要什么,这可能是一种告诉ngStyle 在我明确询问之前不要重新计算的方法。也许ChangeDetectorRef.detach()可以帮忙
【问题讨论】:
-
也许你最好避免使用该函数并将 bg 颜色映射到矩阵数组(或带有键 [row +'-'+col] 的对象)
-
模板中的函数调用是通用的性能杀手。不要这样做,在您的组件中运行该函数一次并将其分配为列上的属性并以这种方式分配。
标签: javascript angular typescript