The function is running on model 3 times

I created a class as a model file

export class Category {
    constructor(
        public name: string,
        public numberOfVisits: number
    ) {
    }

    addVisit(){
        return this.numberOfVisits += 1;
    }
}

This is my component

export class AppComponent {
  category: Category;
  constructor() {
    this.category = new Category('Search', 1);
  }
}

And this is my HTML:

<div class="block">
 {{category.name}}<br />
 Number of visits: {{category.addVisit()}}
</div>

When I am refreshing the page I get: Number of visits: 3 However, I expect to get 1. When I am debugging, I see that the program is running on the model 3 times. Does anyone have any idea, why?

1 answer

  • answered 2018-02-13 02:29 raja reddy

    Create a separate getter for getting visits count. Update your model as shown below:

    export class Category {
        constructor(
            public name: string,
            public numberOfVisits: number
        ) {
        }
        addVisit(){
            return this.numberOfVisits += 1;
        }
        getVisits(){
          return this.numberOfVisits;
        }
    }
    

    And your sample template:

    <div class="block">
      <button (click)="category.addVisit()">addVisit +1</button>
      <br> {{category.name}}
      <br /> Number of visits: {{category.getVisits()}}
    </div>
    

    And please check the working plunker