6

Here the statements in test method is called multiple times. Why is this happening? Is DOM is recreated by AngularJS2 multiple times?

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `<div>Method Call {{test()}}</div>>`
})

export class AppComponent { 
    name = 'Angular';
    test() {
       console.log("Test is called");
    }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Prajeet Shrestha
  • 7,978
  • 3
  • 34
  • 63

1 Answers1

18

{{test()}} is evaluated every time Angular runs change detection, which can be quite often.

Binding to function or methods from the view is discouraged. Prefer assigning the result of the method call to a property and bind to this property instead.

@Component({
  selector: 'my-app',
  template: `<div>Method Call {{someValue}}</div>>`
})

export class AppComponent { 
    ngOnInit() {
      this.test();
    }
    name = 'Angular';
    test() {
       this.someValue = "Test is called";
    }
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567