0

In the Angular 4,

app.component.html

<div>Counter: {{GetCount()}}</div>

app.component.ts

    import { Component, OnInit } from '@angular/core';
        @Component({
          selector: 'app-root',
          templateUrl: './app.component.html',
          styleUrls: ['./app.component.css']
        })
        export class AppComponent  implements OnInit {
    constructor() {

      }

     ngOnInit()
     {

     }
   counter:number = 1;

  GetCount(): any {

    this.counter++;
    return this.counter;

  }
}

My output was on the screen:

Counter: 4

How it is possible? I am calling the GetCount method only once in my html and It's hitting 4 times when I put break point in the method. What I am doing wrong here.

Karthikeyan
  • 299
  • 1
  • 10
  • 25

3 Answers3

3

Nothing wrong. Angular calls your expressions multiple times in order to check if value changed.

Olezt
  • 1,638
  • 1
  • 15
  • 31
2

when you call a method like that from the html, every angular change detection cycle this method gonna call.

if you want to call this method only once, i suggest call it from the ngOnInit

ngOnInit(){
      GetCount()
}
 counter:number = 1;

 GetCount(): void{    
   this.counter++;     
 }

in the html print the couter variable

<div>Counter: {{counter}}</div>
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
2

Angular is gonna evaluate that expression every time it checks for changes, which is associated with the DoCheck lifecycle hook.

Osman Cea
  • 1,467
  • 9
  • 18