Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

{{ call() }} in template executes the method block multiple times?

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");
    }
}
like image 231
Prajeet Shrestha Avatar asked Dec 01 '16 08:12

Prajeet Shrestha


1 Answers

{{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";
    }
}
like image 193
Günter Zöchbauer Avatar answered Nov 04 '22 18:11

Günter Zöchbauer