Home > Software engineering >  Angular double curly braces expressions being executed multiple times on mouse down and up
Angular double curly braces expressions being executed multiple times on mouse down and up

Time:05-19

In our Angular app, given code like the following:

<div>{{ aGetProperty }}</div>

<div>{{ aMethod() }}</div>

Whenever I click anywhere on the page, these expressions are evaluated multiple times. That is, if I put a console.log('hello') in aMethod, every time I press down on either the left or right mouse button, hello is outputted to console multiple times and again multiple times on mouse up.

Anyone know what could be causing this issue? I have not bound any click, mouse up/down events for the component or anything above it (as far as I can tell). Thanks.

CodePudding user response:

Angular actually patches the browsers's low-level API: for example the addEventListener is patched to check for changes in DOM and rerender the view. Thus, when you click on the DOM elements Angular will run change detection and your method calls in DOM will get executed. In other words: it's a bad practice to bind methods from DOM - unless it's explicitly an on/click event - because the method will get executed on each change detection in lifecycle. Of course, sometimes you'd indeed want some of your methods to fire on each change, but make sure that's exactly what you want.

  • Related