Reputation: 2314
Template:
<tbody>
<tr>
<td>{{getRand()}}</td>
<td>{{getRand()}}</td>
</tr>
</tbody>
Method:
getRand(){
return Math.floor(Math.random()*100);
}
Error:
Expression has changed after it was checked. Previous value: '90'. Current value: '32'.
Can anyone explain why this error occurs? Why can't I call this method multiple times?
Upvotes: 1
Views: 151
Reputation: 42669
This is how Angular change detection works!
The change detection algorithm in Angular, goes through the component tree at specific times (some events), to determines what has changed.
It then update the UI based on the model changes and UI bindings.
In dev mode (look at https://angular.io/docs/ts/latest/api/core/index/enableProdMode-function.html and what exactly happens when `enableProdMode()` and What is difference between production and development mode in Angular2?) this component walk is performed twice just to make sure that model is stable after the changes. In your case the function you use for binding is not side-effect free, as each invocation of the function returns a different value.
As a rule of thumb, use side-effect free bindings.
Upvotes: 1
Reputation: 2552
Do you have server side rendering on?
Not sure about angular but on React, if you have server side rendering, the rendered values will be re-evaluated on the client side and it will raise some errors/warnings about it.
Upvotes: 1