模板中的{{call()}}多次执行方法块?

时间:2016-12-01 08:53:57

标签: angular lifecycle-hook

这里多次调用测试方法中的语句。为什么会这样? DOM是由AngularJS2多次重建的吗?

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");
    }
}

1 个答案:

答案 0 :(得分:8)

每次Angular运行变化检测时都会对

{{test()}}进行评估,这种情况经常发生。

不鼓励从视图绑定到函数或方法。首选将方法调用的结果分配给属性,然后绑定到此属性。

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

export class AppComponent { 
    ngOnInit() {
      this.test();
    }
    name = 'Angular';
    test() {
       this.someValue = "Test is called";
    }
}