1

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?

userqwert
  • 2,193
  • 5
  • 28
  • 50

2 Answers2

1

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.

Hasan
  • 2,444
  • 3
  • 30
  • 44
  • Nah its all frontend using angular-cli. I'm guessing the digest cycle is noticing it's changed and thinking that it's an error for some reason. – userqwert Jan 30 '17 at 17:09
1

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.

Community
  • 1
  • 1
Chandermani
  • 42,589
  • 12
  • 85
  • 88
  • Ah I see. How would I go about producing random numbers for an array of indeterminate length without triggering side effects? – userqwert Jan 31 '17 at 09:20
  • This does not break anything as such. But assuming you want this random number generated only once, it would be better you do it in the controller in some sort of array and then bind to the array. – Chandermani Jan 31 '17 at 15:04