View render multiple time

I created a new ionic 3 project. In my HomePage, i have only one varible and one function:

count = 0;
printLog() {
    console.log("count", ++this.count);

In template home.html i call this function by interpolation binding:

It is my whole code. In the console i see the log:
As we can see the printLog function were called 9 times. I can’t understand why. Can someone tell me why and how it work?
Many thanks!

Don’t do this. What are you actually trying to achieve?

I usually do this when want to format the output like that: {{formatDateString(birthDay)}}. Why i should not do this?

It’s generally inefficient to call functions from templates, so preferably one would put anything referenced from a template into a property.

It is impermissible to modify state in a function referenced by a template. Your ++this.count throws a monkey wrench into Angular’s change detection.

Could you please explain it more detailedly?
I think the problem is not in my ++this.count. When i remove ++, it still called 9 times.
I have added some function to track angular lifecycle:

ngDoCheck() {
ngAfterViewChecked() {
printLog() {
    console.log("vew redering");

In the console, i get it
As we can see, anglar do check 5 times when the app start and i can’t understand why.

I think you’ve discovered this yourself. The function gets called many times. You are best served by either making it as light as possible or not being a function at all, but rather a property. If it’s a property, Angular’s change detection can know when it changes. If it’s a function, it can’t, and must call it every time.

I don’t think it’s a very productive exercise to try to make app code micromanage Angular, but if you insist on doing so, you can investigate OnPush change detection.

Yeah. Now i agree that should not call function from template. But, i am considering that if i don’t use any function in template, does the view still re-render so many times? Is there any way to check it?

I don’t think I would characterize it as “re-rendering”, but no. Angular stores the old value of the property, and compares it to the new value during each round of change detection.

Thanks for helping me. Now i understand the mechanism more clearly.

1 Like