Search code examples
angularangular-template

Why do the rest of methods in this template get called when I increment this number input in angular?


If you take a look on this stackblitz code: https://stackblitz.com/edit/angular-ivy-xvxgrh at line 7 in file recipie-ingredients.component from recipie-ingredients module you can see that I have a number input. this means that each time I increment the value of that input number that modifyPeopleCount method is called. But when I increment that input number the rest of the methods in that angular template are also called. For example adjustIngredientAmount is also called. How is this feature called in angular? Why isn't only the modifyPeopleCount method called?


Solution

  • This is because of Angular's "change detection".

    Let's say in the HTML template you have this:

    <b> {{ adjustIngredientAmount(entry) }}</b>
    

    So the value that should be shown is the outcome of the function adjustIngredientAmount with the parameter entry. But the only logical way that a programming language can know the outcome of a function is to call/execute it.

    Think about this as if the function is a complete black-box and you can not look into it. So you HAVE to execute it to get the value.

    Angular has "change detection" running (won't link an article as there are so many, just look for something that suits you to read) to somewhat "smart" guess when an outcome of a function could have changed.

    So basically: Whatever function you use in your template for displaying things (or also if used in ngIf, ngFor etc) angular will execute those functions whenever "something" changes, because maybe the outcome of a function is different then.

    The "something" is not that easy to explain, so just read articles about it. You can also change the strategy angular uses to avaluate when something has maybe changed.

    Also, there are ways to manually "tell" angular that something has changed.

    It's not "wrong" that functions are called like this but if your app grows you should think about patterns that avoid calling functions inside the html, because those calls can grow exponentially later :)


    edit: Adding what i commented under some other answer:

    One solution could be that OP is calculating these values when the array is created and adding those calculated values as some meta-data to the array. He then can directly access them. But it's always a tradeoff. Functions inside the template save memory but cost execution power. The other way costs memory but saves execution power.