【问题标题】:{{ call() }} in template executes the method block multiple times?模板中的 {{ call() }} 多次执行方法块?
【发布时间】:2017-04-15 19:55:15
【问题描述】:

这里测试方法中的语句被多次调用。为什么会这样? 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");
    }
}

【问题讨论】:

    标签: angular lifecycle-hook


    【解决方案1】:

    {{test()}} 每次 Angular 运行变更检测时都会被评估,这可能非常频繁。

    不鼓励从视图绑定到函数或方法。最好将方法调用的结果分配给一个属性并绑定到该属性。

    @Component({
      selector: 'my-app',
      template: `<div>Method Call {{someValue}}</div>>`
    })
    
    export class AppComponent { 
        ngOnInit() {
          this.test();
        }
        name = 'Angular';
        test() {
           this.someValue = "Test is called";
        }
    }
    

    【讨论】:

    猜你喜欢
    • 2019-12-28
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-13
    • 2021-02-06
    相关资源
    最近更新 更多