Angular Performance: DOM Event causes unnecessary function calls

后端 未结 1 360
长发绾君心
长发绾君心 2020-12-04 00:58

I have a simple page with an input element that has a DOM event (input). The HTML page also calls a function that just outputs something via console.log. Now when I open the

相关标签:
1条回答
  • 2020-12-04 01:39

    Since you're calling a function in one of the data-binding syntaxes, whenever Angular performs Change Detection, it will call this method.

    Before for a function, anything that cases is the value that it returns. And for Angular to know that the returned value has changed, Angular will have to run it.

    This is the exact same issue that people have raised a several questions here:

    1. Angular: Prevent DomSanizer from updating on DOM Events

    2. Angular performance: ngStyle recalculates on each click on random input

    3. Angular 7 ,Reactive Form slow response when has large data

    You might want to read through these threads to understand what's going on here and how you can fix this issue.


    The solution is to basically design your implementation in such a way, that it never calls a method in one of the data-binding syntaxes, i.e.

    1. In String Interpolation - {{ methodCall() }}
    2. In Property Binding - [propertyName]="methodCall()"
    3. In Attribute Binding - [class.className]="methodCall()" / [style.style-name]="methodCall()"

    An alternative solution is do move this code to a Child Component and configure the changeDetectionStrategy on that child component to ChangeDetectionStrategy.OnPush

    0 讨论(0)
提交回复
热议问题